2018-05-25

2018-05-25  本文已影响0人  aquawj

题目

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:3Explanation:Three palindromic strings: "a", "b", "c".

Example 2:

Input:"aaa"Output:6Explanation:Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

The input string length won't exceed 1000.

解法

1. Extend palindrome

时间:O(n^2), 空间O(1)

'''
class Solution {
int count = 0;
public int countSubstrings(String s) {
if(s == null || s.length() == 0) return 0;
int n = s.length();
for(int i = 0; i < n; i++){
checkAdj(i, i, n, s);
checkAdj(i, i + 1, n, s);
}
return count;
}

public void checkAdj(int start, int end, int n, String s){
   int k = 0;
    while(k <= start && k < n - end && s.charAt(start - k) == s.charAt(end + k)){
        count++;
        k++;
    } 
}

}
'''

2. DP

'''
public int countSubstrings(String s) {
int n = s.length();
int res = 0;
boolean[][] dp = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
if(dp[i][j]) ++res;
}
}
return res;
}
'''

上一篇 下一篇

猜你喜欢

热点阅读