Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
思路一:(超时)简单的截取长度为length(length递减)的字串,判断其是否为回文串。第一个满足要求的回文串最长。
public class Solution { public String longestPalindrome(String s) { int m=s.length(); String ans=null; if(m==0) return s; if(m==1) return s; for(int length=m;length>=0;length--){ for(int i=0;i+length-1<m;i++){ ans=s.substring(i,i+length-1); if(isPalindromic(ans)) return ans; } } return ans; } public static boolean isPalindromic(String l){ int k=l.length(); for(int i=0;i<k/2;i++){ if(l.charAt(i)!=l.charAt(k-1-i)) return false; } return true; } }
思路二:动态规划。dp[i][j]=true when dp[i+1][j-1]=true&&s.charAt(i)==s.charAt(j);
public class Solution { public String longestPalindrome(String s) { int n = s.length(); int start = 0; int maxLength = 1; boolean dp[][] = new boolean[n+1][n+1]; for (int i = 0; i < n; i++) { dp[i][i] = true; } for (int i = 0; i < n-1; i++) { if (s.charAt(i) == s.charAt(i+1)) { dp[i][i+1] = true; start = i; maxLength = 2; } } for (int len = 3; len <= n; len++) { for (int i = 0; i < n-len+1; i++) { int j = i+len-1; if (s.charAt(i) == s.charAt(j)&& dp[i+1][j-1]) { dp[i][j] = true; start = i; maxLength = len; } } } return s.substring(start, start+maxLength); } }
思路三:http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html这个方法效率最高,现在的水平还想不出这样的方法。
时间: 2024-12-22 14:06:07