题目描述
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.
题意分析
找出回文串的个数
算法分析
从每个位置i开始左右扩展,如果左右相等,则count++,继续扩展,否则结束扩展。
扩展的时候还要分奇数串和偶数串。
复杂度为
O(n2)
具体实现
class Solution {
public:
int countSubstrings(string s) {
int count = s.size();
for (int i = 0; i < s.size(); i++) {
int left = i - 1, right = i + 1;
while (left >= 0 && right < s.size() && (s[left--] == s[right++]) )
count++; // odd
left = i - 1, right = i;
while (left >= 0 && right < s.size() && (s[left--] == s[right++]) )
count++; // even
}
return count;
}
};
更多
网友Deribs4的博客 中提到一种复杂度为 O(n) 的算法