Leetcode 647. Palindromic Substrings
Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Input: s = "abc"
Output: 3
Explanation: "a", "b", and "c" are palindromic substrings.
Input: s = "aaa"
Output: 6
Explanation: "a", "a", "a", "aa", "aa", and "aaa" are palindromic substrings.
s
will be between 1 and 1000.s
consists of only lowercase English letters.s
will consist solely of lowercase English letters.To solve this problem, we can use two main approaches:
dp
where dp[i][j]
will be true
if the substring s[i:j+1]
is a palindrome.For simplicity and efficiency, we will use the Expand Around Center approach.
Here’s the code for the Expand Around Center
approach:
#include <iostream>
#include <string>
class Solution {
public:
int countSubstrings(std::string s) {
int n = s.length();
int count = 0;
// Helper function to count palindromes around a center.
auto countPalindromesAroundCenter = [&](int left, int right) {
while (left >= 0 && right < n && s[left] == s[right]) {
count++;
left--;
right++;
}
};
// Expand around each character and each pair.
for (int i = 0; i < n; i++) {
countPalindromesAroundCenter(i, i); // Odd length palindromes
countPalindromesAroundCenter(i, i + 1); // Even length palindromes
}
return count;
}
};
int main() {
Solution sol;
std::string s1 = "abc";
std::string s2 = "aaa";
std::cout << "Number of palindromic substrings in " << s1 << " is " << sol.countSubstrings(s1) << std::endl;
std::cout << "Number of palindromic substrings in " << s2 << " is " << sol.countSubstrings(s2) << std::endl;
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?