comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
Medium |
1323 |
Weekly Contest 389 Q2 |
|
You are given a string s
and a character c
. Return the total number of substrings of s
that start and end with c
.
Example 1:
Input: s = "abada", c = "a"
Output: 6
Explanation: Substrings starting and ending with "a"
are: "abada"
, "abada"
, "abada"
, "abada"
, "abada"
, "abada"
.
Example 2:
Input: s = "zzz", c = "z"
Output: 6
Explanation: There are a total of 6
substrings in s
and all start and end with "z"
.
Constraints:
1 <= s.length <= 105
s
andc
consist only of lowercase English letters.
First, we can count the number of character
Each character
Therefore, the answer is
The time complexity is
class Solution:
def countSubstrings(self, s: str, c: str) -> int:
cnt = s.count(c)
return cnt + cnt * (cnt - 1) // 2
class Solution {
public long countSubstrings(String s, char c) {
long cnt = s.chars().filter(ch -> ch == c).count();
return cnt + cnt * (cnt - 1) / 2;
}
}
class Solution {
public:
long long countSubstrings(string s, char c) {
long long cnt = ranges::count(s, c);
return cnt + cnt * (cnt - 1) / 2;
}
};
func countSubstrings(s string, c byte) int64 {
cnt := int64(strings.Count(s, string(c)))
return cnt + cnt*(cnt-1)/2
}
function countSubstrings(s: string, c: string): number {
const cnt = s.split('').filter(ch => ch === c).length;
return cnt + Math.floor((cnt * (cnt - 1)) / 2);
}