Palindromic longest substring --dp

Given a string s, s to find the longest substring palindromic. You can assume that the maximum length of 1000 s.

Example 1:

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

Enter: "cbbd"
Output: "bb"

Topics address

The main requirement palindromic string from the center of symmetry.
For example "aba" "bb" "c ". Suppose that for a character string "a ??? a" assumes the starting position is i, the end position is J
S [I] = S [J], the initial conditions are satisfied, but still can not conclude that the palindrome, because the intermediate uncertain. His status 1 ~ j-1 This smaller range is determined by i +. So the use of dp. DP [] [] i ~ j representative of the state of the palindrome. So have

dp[j][i]=dp[j+1][i-1];

According to the above idea, to traverse

class Solution {
    public String longestPalindrome(String s) {
      int len=s.length();
if(len<2){
    return s;
    
}
      boolean dp[][] =new boolean [len][len];

      //单个字符串肯定是回文
      for(int i=0;i<len;i++){
          dp[i][i]=true;
      } 
      
      int max=1;
      int start=0;
      //j-i 形成区间 j在左边 i在右边 
      for(int i=1;i<len;i++){
          for(int j=0;j<i;j++){
            if(s.charAt(i)==s.charAt(j)){
                if(i-j<3){
                    dp[j][i]=true;
                }
                else{
                    //范围过大,缩圈,分析小范围
                    dp[j][i]=dp[j+1][i-1];

                }
            }else{
                dp[j][i]=false;
            }
            

            //统计长度
            if(dp[j][i]){
                int temp =i-j+1;
                if(temp>max){
                    max=temp;
                    start=j;
                }
            }



          }
      }
       System.out.println("max is "+max);

        return  s.substring(start, start + max); 

    } 

}
Published 68 original articles · won praise 3 · Views 5210

Guess you like

Origin blog.csdn.net/Hqxcsdn/article/details/104479924
Recommended