You are given a 0-indexed string s consisting of only lowercase English letters. Return _the number ofsubstrings in _sthat begin and end with thesame character.
A substring is a contiguous non-empty sequence of characters within a string.
Input: s ="abcba"Output: 7Explanation:
The substrings of length 1 that start and end with the same letter are:"a","b","c","b", and "a".The substring of length 3 that starts and ends with the same letter is:"bcb".The substring of length 5 that starts and ends with the same letter is:"abcba".
Example 2:
1
2
3
4
5
6
Input: s ="abacad"Output: 9Explanation:
The substrings of length 1 that start and end with the same letter are:"a","b","a","c","a", and "d".The substrings of length 3 that start and end with the same letter are:"aba" and "aca".The substring of length 5 that starts and ends with the same letter is:"abaca".
Example 3:
1
2
3
4
Input: s ="a"Output: 1Explanation:
The substring of length 1 that starts and ends with the same letter is:"a".
For each character, count how many times it appears. For each such character, the number of substrings that start and end with it is count * (count + 1) // 2 (all single letters plus all pairs, triples, etc.).
classSolution {
publiclongnumberOfSubstrings(String s) {
long[] cnt =newlong[26];
for (char c : s.toCharArray()) cnt[c -'a']++;
long ans = 0;
for (int i = 0; i < 26; i++) ans += cnt[i]* (cnt[i]+ 1) / 2;
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funnumberOfSubstrings(s: String): Long {
val cnt = LongArray(26)
for (c in s) cnt[c - 'a']++var ans = 0Lfor (i in0..25) ans += cnt[i] * (cnt[i] + 1) / 2return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defnumberOfSubstrings(self, s: str) -> int:
cnt = [0] *26for c in s:
cnt[ord(c) - ord('a')] +=1 ans =0for x in cnt:
ans += x * (x +1) //2return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnnumber_of_substrings(s: String) -> i64 {
letmut cnt = [0i64; 26];
for c in s.chars() {
cnt[(c asu8-b'a') asusize] +=1;
}
letmut ans =0i64;
for x in cnt.iter() {
ans += x * (x +1) /2;
}
ans
}
}
1
2
3
4
5
6
7
8
9
classSolution {
numberOfSubstrings(s: string):number {
constcnt=new Array(26).fill(0);
for (constcofs) cnt[c.charCodeAt(0) -97]++;
letans=0;
for (constxofcnt) ans+=x* (x+1) /2;
returnans;
}
}