题目
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例1
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
示例2
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
注意
- 输入的字符串长度不会超过1000。
思路
- 回文子串,可能有一个中心,也可能有两个中心。遍历每个中心,去计算以它们为中心的回文子串的数量。
代码
class Solution {
private:
int cnt = 0;
public:
int countSubstrings(string s) {
if ( s.size() == 0 ) return 0;
for ( int i = 0; i < s.size(); ++i ) {
helper( s, i, i );
helper( s, i, i + 1 );
}
return cnt;
}
void helper( const string& s, int left, int right ) {
while( left >= 0 && right < s.size() && s[left] == s[right] ) {
++cnt;
--left;
++right;
}
return;
}
};