【leetcode5】 5. Longest Palindromic Substring 解题报告

  • 关键字:动态规划、回文字符串
  • 难度:Medium
  • 题目大意:输出一个字符串的最长回文子串
题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"
解题思路:
  • 思路一:
    以每一个字符为中心,往两边扩散来找,需要考虑字符串长度为奇 数和偶数的情形;
  • 思路二:动态规划,以p(i,j)表示从字符串下标i到下标j字符是否为回文串,则可分情况讨论:
    • i==j时:
      p(i, j) = true
    • j-i=1时:
      p(i, j)=s.charAt(i)==s.charAt(j) j-i=1;
    • j-i>1时:
      p(i, j)=s.charAt(i)==s.charAt(j)&&( j-i<2||p(i+1,j-1));

填充dp数组时,注意逆序填充,可结合下图例子理解:

逆序填充DP.jpeg

解法1:
class Solution {
        public String longestPalindrome(String s) {
        if(s==null||s.length()==0) return s;
        int len = s.length();
        int maxLen = 1;
        int start = 0;
        for(int i=0;imaxLen) {
                maxLen = cur;
                start = i-(maxLen-1)/2;
            }
        }

        return s.substring(start,start+maxLen);
    }
    private int process(String s, int l, int r,int maxLen){
        while(l>=0&&r
解法2:
class Solution {
    public static String longestPalindrome(String s) {
        if(s==null||s.length()==0) return s;
        int len = s.length();
        boolean [][] dp = new boolean[len+1][len+1];
        int maxLen = 1;
        int start = 0;
        //初始化i==j时dp数组的值为true
        for(int i=1;i0;i--) {
            for(int j=len;j>i;j--) {
                if(s.charAt(i-1)==s.charAt(j-1)&&(dp[i+1][j-1]||j-i<2)) {
                    dp[i][j] = true;
                    if(maxLen

你可能感兴趣的:(【leetcode5】 5. Longest Palindromic Substring 解题报告)