Skip to content

Commit 5912ca5

Browse files
authored
Create 2083-substrings-that-begin-and-end-with-the-same-letter.js
1 parent 1ffeb41 commit 5912ca5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const numberOfSubstrings = function(s) {
6+
const hash = {}
7+
const n = s.length
8+
for(let i = 0; i < n; i++) {
9+
const ch = s[i]
10+
if(hash[ch] == null) hash[ch] = []
11+
hash[ch].push(i)
12+
}
13+
14+
let res = 0
15+
const keys = Object.keys(hash)
16+
keys.forEach(k => {
17+
res += helper(k)
18+
})
19+
20+
return res
21+
22+
23+
function helper(k) {
24+
const arr = hash[k]
25+
const len = arr.length
26+
return len * (len + 1) / 2
27+
}
28+
};

0 commit comments

Comments
 (0)