Two liners using LINQ
You can use LINQ to get the count of instances in one line. Call it N. Then a bit of math: you're looking for combination of N, 2 by 2, which would be the formula N! / (2! * (N-2)!) and if you simplify you get N*(N-1)/2. You also have to add N to account for single-letters strings. Code is down below, cheers, ACC.
You are given a string s and a character c. Return the total number of substrings of s that start and end with c.
public long CountSubstrings(string s, char c) { long n = s.Where(k => k == c).Count(); return n + (n * (n - 1) / 2); }
Comments
Post a Comment