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.
找所有可能的回文数量
自己的思路for循环遍历,依次substring,然后判断是否是回文即可
public int countSubstrings(String s) {
if(s == null || s.isEmpty()){
return 0;
}
int result = 0 ;
for(int i = 0; i< s.length();i++){
for(int j = i+1; j< s.length()+1;j++){
if(isPalindromic(s.substring(i,j))){
result ++;
}
}
}
return result;
}
private boolean isPalindromic(String a){
for(int i = 0, j = a.length()-1; i
这也是一种简单的方式
我们知道回文都有一个中心,要么这个中心是一个字符,要么是两个字符,顺序遍历每一个中心,利用如果S[i]是回文并且S[i-1]==S[i+1]的话,那么S[i-1,i+1]也是回文的推论可以有如下算法
public int countSubstrings(String S) {
int N = S.length(), ans = 0;
for (int len = 0; len <= 2*N-1; ++len) {
//当left==right的时候,中心是一个字符
//当left=right-1的时候,中心是两个字符
//将len/2和len % 2可以保证left和right每当len为偶数时候left=right,当len为奇数的时候
//left=right-1,也就是left/right交替增长,这样的话len的最大值就必须是2n-1的长度,不然后半部分元素
//遍历不到
int left = len / 2;
int right = left + len % 2;
//如果S.charAt(left) == S.charAt(right) ,继续比较S.charAt(left-1) == S.charAt(right+1)
//当然继续比较的条件是left和right不突破边界值
while (left >= 0 && right < N && S.charAt(left) == S.charAt(right)) {
ans++;
left--;
right++;
}
}
return ans;
}
还有更简单的Manacher's ALGORITHM 时间复杂度可以达到O(n),有点复杂,研究透了专门写一篇