Skip to content

Commit c60723c

Browse files
committed
Palindromic Substrings solution
1 parent 65d5e64 commit c60723c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

palindromic-substrings/kimyoung.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
var countSubstrings = function (s) {
2+
let result = 0;
3+
for (let i = 0; i < s.length; i++) {
4+
let left = i,
5+
right = i; // odd length substrings
6+
helper(s, left, right);
7+
8+
(left = i), (right = i + 1); // even length substrings
9+
helper(s, left, right);
10+
}
11+
function helper(s, l, r) {
12+
// increment result and keep expanding left and right, while left and right indexes are within range and they're equal
13+
while (l >= 0 && r <= s.length && s[l] === s[r]) {
14+
result++;
15+
l--;
16+
r++;
17+
}
18+
}
19+
return result;
20+
};
21+
22+
// test cases
23+
console.log(countSubstrings("abc")); // 3
24+
console.log(countSubstrings("aaa")); // 6
25+
console.log(countSubstrings("a")); // 1
26+
console.log(countSubstrings("")); // 0
27+
28+
// space - O(1) - constant variable `result`
29+
// time - O(n^2) - iterating through the string and expanding both ways

0 commit comments

Comments
 (0)