[LeetCode] Substrings That Begin and End With the Same Letter

2083. Substrings That Begin and End With the Same Letter

You are given a 0-indexed string s consisting of only lowercase English letters. Return the number of substrings in s that begin and end with the same character.

A substring is a contiguous non-empty sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
long long numberOfSubstrings(string s) {
vector<int> counter(26,0);
long long res = 0;
for(auto& ch : s)
res += ++counter[ch-'a'];
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/28/PS/LeetCode/substrings-that-begin-and-end-with-the-same-letter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.