码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 5:Longest Palindromic Substring(最长回文串)

时间:2015-06-12 00:33:10      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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;
        }
}
View Code

思路二:动态规划。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);  
        
    }
    
    
}
View Code

思路三:http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html这个方法效率最高,现在的水平还想不出这样的方法。

LeetCode 5:Longest Palindromic Substring(最长回文串)

标签:

原文地址:http://www.cnblogs.com/gonewithgt/p/4570436.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!