天天看点

5. Longest Palindromic Substring&&647. Palindromic Substrings

5. Longest Palindromic Substring&&647. Palindromic Substrings

诚然,不言暴力法。动态规划和中心扩展法较为合适。

5. Longest Palindromic Substring&&647. Palindromic Substrings
class Solution {
public String longestPalindrome(String s) {
  int n = s.length();
  String res = "";
    
  boolean[][] dp = new boolean[n][n];
    
  for (int i =n; 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] && (j - i + 1 > res.length())) {
        res = s.substring(i, j + 1);
      }
    }
  }
    
  return res;
}
}
           

 中心扩展法(分奇数和偶数两种情况)

class Solution{
public String longestPalindrome(String s) {
    if (s == null || s.length() < 1) return "";
    int start = 0, end = 0;
    for (int i = 0; i < s.length(); i++) {
        int len1 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(s, i, i + 1);
        int len = Math.max(len1, len2);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }
    return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right) {
    int L = left, R = right;
    while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
        L--;
        R++;
    }
    return R - L - 1;
}
}
           
5. Longest Palindromic Substring&amp;&amp;647. Palindromic Substrings

暴力法就不说了。

class Solution {
    public int countSubstrings(String s) {
        int count=0;
        for(int i=0;i<s.length();i++){
            for(int j=i+1;j<=s.length();j++)
                if(palindromic(s.substring(i,j)))
                    count++;
        }
        return count;
        
    }
    public boolean palindromic(String sub){
        int l=0,r=sub.length()-1;
        while(l<r){
            if(sub.charAt(l)!=sub.charAt(r))
                return false;
            l++;
            r--;
        }
        return true;
    }
}
           

 对于回文字符,中心扩展法很常用。

class Solution {
    int count;
    public int countSubstrings(String s) {
        if(s==null || s.length()==0) return 0;
        count = 0;
        for(int i=0;i<s.length();i++){
            extendpalindrome(s,i,i);
            extendpalindrome(s,i, i+1);
        }
        return count;
    }
    
    public void extendpalindrome(String s, int i, int j){
        while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){
            count++;
            i--;
            j++;
        }
    }
}