Description
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: “abc”
Output: 3
Explanation: Three palindromic strings: “a”, “b”, “c”.
Example 2:
Input: “aaa”
Output: 6
Explanation: Six palindromic strings: “a”, “a”, “a”, “aa”, “aa”, “aaa”.
Note:
The input string length won’t exceed 1000.
分析
根据题意可知,每个单独的字符都是回文串。可以这么定义状态转移方程:以该字符为中心向两边展开,如果左边字符与右边字符相同,那么连起来又是一个回文串。
基于这种思想,写出了如下代码:
class Solution {
public:
int countSubstrings(string s) {
int count = 0, left, right;
for (int i = 0; i < s.size(); i++) {
left = right = i;
while (left >= 0 && right < s.size() && s[left] == s[right]) {
count++;
left--;
right++;
}
}
return count;
}
};
但是上面的代码是错误的,对于aaa的输入,它只能找出4种回文串,实际上有6种。这是因为考虑少了一种情况。
回文串的长度可以是奇数,也可以是偶数。上面的代码只考虑到了长度是奇数的情况,需要进行重构。最终代码如下:
class Solution {
public:
int countSubstrings(string s) {
count = 0;
for (int i = 0; i < s.size(); i++) {
countSubstringsWithCenterInRange(s, i, i);
countSubstringsWithCenterInRange(s, i, i+1);
}
return count;
}
private:
int count;
void countSubstringsWithCenterInRange(string s, int from, int to) {
while (from >= 0 && to < s.size() && s[from] == s[to]) {
count++;
from--;
to++;
}
}
};