[leetcode]5. Longest Palindromic Substring最长回文子串

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"

题意:

最长回文子串

思路:

dp经典题,需要熟练掌握

代码:

 1 class Solution {
 2     public String longestPalindrome(String s) {
 3         String res = "";
 4         boolean[][] dp = new boolean[s.length()][s.length()];
 5         int max = 0;
 6         for(int j= 0; j < s.length(); j++){
 7             for(int i = 0; i<=j; i++){
 8                 dp[i][j] = s.charAt(i) == s.charAt(j) && ((j-i<=2)||dp[i+1][j-1]);      
 9                 if(dp[i][j] && (j-i+1>max)){
10                 max = j- i + 1;
11                 res = s.substring(i,j+1);
12             }
13             }  
14         }     
15        return res;     
16     }
17 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9207588.html