[LeetCode] Count Substrings Starting and Ending with Given Character

3084. Count Substrings Starting and Ending with Given Character

You are given a string s and a character c. Return the total number of substrings of s that start and end with c.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
long long countSubstrings(string s, char c) {
long long cnt = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == c) cnt++;
}
return cnt * (cnt + 1) / 2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/17/PS/LeetCode/count-substrings-starting-and-ending-with-given-character/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.