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.
分析
题目的意思是:判断一个字符串里有多少不同的回文子串。
- 把string的每一个位置当作回文子串的中心位置串,如果回文子串长度为奇数是,中间位置只有一个i;如果回文子串为偶数时,中间未知就为i,i+1;然后向两边拓展,这样遍历完以后就能得到所有的情况。
C++实现
class Solution {
public:
int countSubstrings(string s) {
if(s.empty()) return 0;
int count=0;
for(int i=0;i<s.length();i++){
helper(s,i,i,count);
helper(s,i,i+1,count);
}
return count;
}
private:
void helper(string s,int i,int j,int &count){
while(i>=0&&j<s.length()&&(s[i]==s[j])){
i--;
j++;
count++;
}
}
};
Python实现
长度为n的字符串会生成2n-1组回文中心[l,r],其中l=i//2, r=i//2+i%2。只要从 0 到2n-2遍历 i,就可以得到所有可能的回文中心,这样就把奇数长度和偶数长度两种情况统一起来了。
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
res = 0
for i in range(2*n-1):
left = i//2
right = i//2+i%2
while left>=0 and right<n and s[left]==s[right]:
left-=1
right+=1
res+=1
return res