Skip to content

Commit 0d99a90

Browse files
authored
Create substrings-that-begin-and-end-with-the-same-letter.cpp
1 parent cc5655a commit 0d99a90

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
long long numberOfSubstrings(string s) {
7+
unordered_map<char, int> cnt;
8+
int64_t result = 0;
9+
for (const auto& c : s) {
10+
result += ++cnt[c];
11+
}
12+
return result;
13+
}
14+
};
15+
16+
// Time: O(n)
17+
// Space: O(1)
18+
class Solution2 {
19+
public:
20+
long long numberOfSubstrings(string s) {
21+
unordered_map<char, int64_t> cnt;
22+
23+
for (const auto& c : s) {
24+
++cnt[c];
25+
}
26+
int64_t result = 0;
27+
for (const auto& [_, v] : cnt) {
28+
result += v * (v + 1) / 2;
29+
}
30+
return result;
31+
}
32+
};

0 commit comments

Comments
 (0)