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.


Count Substrings Starting and Ending with Given Character - LeetCode

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

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval