題目:
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。
程式碼如下:
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)
程式碼如下:
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