LeetCode解題報告--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, and there exists one unique longest palindromic substring.
題目來源:https://leetcode.com/problems/longest-palindromic-substring/

題意:給定某一字符串,找到最長的迴文子串!(注意:最大回文子串是唯一,即一個字符串不能同時存在多個最長迴文子串)

解法:從長度爲len (len = s.length(), len = s.length() –)開始尋找該字符串的子串,一旦在某一len值找到符合要求子串str,則該str就是要找的最長迴文子串,其他長度的迴文子串則不需要考慮。

/**
 * 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.
 * @author ganyee
 *
 */
public class LongestPalindromicSubstring {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(longestPalindrome("abaaba "));
    }

     public static String longestPalindrome(String s) {
            String maxStr = "";
            for(int i = s.length();i >= 0;i --){
                maxStr = isPalindrom(s, i);
                if(maxStr.length() !=0)
                    break;
            }
            return maxStr;
        }

     public static String isPalindrom(String s,int len){
         int i = 0;
         StringBuffer str = new StringBuffer(s);
         String str1;
         String str2;
         String str3 = "";
         while(i + len <= s.length()){
             str1 = str.substring(i,i + len).toString();
             StringBuffer str4 = new StringBuffer(str1);
             str2 = str4.reverse().toString();
             if(str1.equals(str2) && str3.length() < str1.length()){
                 str3 = str1;
                 break;
             }
             else{
                 i ++;
             }
         }
         return str3;
     }
}

另解:引自
1)http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
2)http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章