5. Longest Palindromic Substring&&647. Palindromic Substrings

5. Longest Palindromic Substring&&647. Palindromic Substrings_第1张图片 

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

5. Longest Palindromic Substring&&647. Palindromic Substrings_第2张图片 

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&&647. Palindromic Substrings_第3张图片

暴力法就不说了。

class Solution {
    public int countSubstrings(String s) {
        int count=0;
        for(int i=0;i

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

class Solution {
    int count;
    public int countSubstrings(String s) {
        if(s==null || s.length()==0) return 0;
        count = 0;
        for(int i=0;i=0 && j

 

你可能感兴趣的:(字符串,动态规划)