Overview
Given a string s, return the number of palindromic substrings in it.
A substring is a contiguous sequence of characters within the string. A string is palindromic if it reads the same backward as forward.
Constraints
1 <= s.length <= 1000sconsists of lowercase English letters.
Examples
countSubstrings("abc");
// => 3 ("a", "b", "c")countSubstrings("aaa");
// => 6 ("a", "a", "a", "aa", "aa", "aaa")Solution
Reveal solution
function countSubstrings(s) {
let count = 0;
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) {
count++;
l--;
r++;
}
}
for (let i = 0; i < s.length; i++) {
expand(i, i); // odd-length
expand(i, i + 1); // even-length
}
return count;
}Expand around each center (both odd and even). Each expansion that matches increments the count. O(n²) time, O(1) space.
Resources
palindromic-substrings.js
Palindromic Substrings
mediumcodingAlgorithmsStrings
Overview
Given a string s, return the number of palindromic substrings in it.
A substring is a contiguous sequence of characters within the string. A string is palindromic if it reads the same backward as forward.
Constraints
1 <= s.length <= 1000sconsists of lowercase English letters.
Examples
countSubstrings("abc");
// => 3 ("a", "b", "c")countSubstrings("aaa");
// => 6 ("a", "a", "a", "aa", "aa", "aaa")Solution
Reveal solution
function countSubstrings(s) {
let count = 0;
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) {
count++;
l--;
r++;
}
}
for (let i = 0; i < s.length; i++) {
expand(i, i); // odd-length
expand(i, i + 1); // even-length
}
return count;
}Expand around each center (both odd and even). Each expansion that matches increments the count. O(n²) time, O(1) space.
Resources
NameTopicDifficulty
103 of 103 problems