Skip to content

3084. Count Substrings Starting and Ending with Given Character 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  long long countSubstrings(string s, char c) {
    const int freq = ranges::count(s, c);
    return static_cast<long>(freq) * (freq + 1) / 2;
  }
};
1
2
3
4
5
6
class Solution {
  public long countSubstrings(String s, char c) {
    final long freq = s.chars().filter(ch -> ch == c).count();
    return freq * (freq + 1) / 2;
  }
}
1
2
3
4
class Solution:
  def countSubstrings(self, s: str, c: str) -> int:
    freq = s.count(c)
    return freq * (freq + 1) // 2