Longest Palindromic Substring leetcode java


題目

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.

 

題解

 第一種方法就是挨個檢查,維護全局最長,時間復雜度為O(n3),會TLE。

 代碼如下:

 1  public String longestPalindrome(String s) {
 2  
 3      int maxPalinLength = 0;
 4     String longestPalindrome =  null;
 5      int length = s.length();
 6  
 7      //  check all possible sub strings
 8       for ( int i = 0; i < length; i++) {
 9          for ( int j = i + 1; j < length; j++) {
10              int len = j - i;
11             String curr = s.substring(i, j + 1);
12              if (isPalindrome(curr)) {
13                  if (len > maxPalinLength) {
14                     longestPalindrome = curr;
15                     maxPalinLength = len;
16                 }
17             }
18         }
19     }
20  
21      return longestPalindrome;
22 }
23  
24  public  boolean isPalindrome(String s) {
25  
26      for ( int i = 0; i < s.length() - 1; i++) {
27          if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
28              return  false;
29         }
30     }
31  
32      return  true;
33 }

 

第二種方法“是對於每個子串的中心(可以是一個字符,或者是兩個字符的間隙,比如串abc,中心可以是a,b,c,或者是ab的間隙,bc的間隙,例如aba是回文,abba也是回文,這兩種情況要分情況考慮)往兩邊同時進 行掃描,直到不是回文串為止。假設字符串的長度為n,那么中心的個數為2*n-1(字符作為中心有n個,間隙有n-1個)。對於每個中心往兩邊掃描的復雜 度為O(n),所以時間復雜度為O((2*n-1)*n)=O(n^2),空間復雜度為O(1)。”引自Code ganker(http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html)

代碼如下:

 

 1      public String longestPalindrome(String s) {
 2          if (s.isEmpty()||s== null||s.length() == 1)
 3              return s;
 4      
 5         String longest = s.substring(0, 1);
 6          for ( int i = 0; i < s.length(); i++) {
 7              //  get longest palindrome with center of i
 8              String tmp = helper(s, i, i);
 9             
10              if (tmp.length() > longest.length())
11                 longest = tmp;
12      
13              //  get longest palindrome with center of i, i+1
14              tmp = helper(s, i, i + 1);
15              if (tmp.length() > longest.length())
16                 longest = tmp;
17         }
18      
19          return longest;
20     }
21      
22      //  Given a center, either one letter or two letter, 
23       //  Find longest palindrome
24       public String helper(String s,  int begin,  int end) {
25          while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
26             begin--;
27             end++;
28         }
29          return s.substring(begin + 1, end);
30     }

 Reference:

 http://www.programcreek.com/2013/12/leetcode-solution-of-longest-palindromic-substring-java/

 http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM