最長迴文子串(Longest Palindromic Substring)
阿新 • • 發佈:2018-11-06
題目描述:
給出一個字串(假設長度最長為1000),求出它的最長迴文子串,你可以假定只有一個滿足條件的最長迴文串。
樣例
給出字串 "abcdzdcab"
,它的最長迴文子串為 "cdzdc"
。
O(n2) 時間複雜度的演算法是可以接受的,如果你能用 O(n) 的演算法那自然更好。
原題連結
LeetCode: https://leetcode.com/problems/longest-palindromic-substring/description/
LintCode: http://www.lintcode.com/zh-cn/problem/longest-palindromic-substring/#
解法一:
這種作法可用通過Lintcode的測試,但是無法通過LeetCodepublic class Solution { /* * @param s: input string * * @return: the longest palindromic substring */ public String longestPalindrome(String s) { // write your code here String res = ""; if (s == null || s.length() == 0) { return ""; } for (int i = s.length() - 1; i >= 0; i--) { // i是子字串的長度 int j = 0; while (j + i < s.length()) { if (s.charAt(j) == s.charAt(j + i)) { // 判斷子字串首尾是否相同(第一次篩選) String s2 = s.substring(j, j + i + 1); if (s2.length() > res.length()) { // 判斷子字串長度是否比上一個迴文子串長(第二次篩選) if (isPalindrome(s2)) { // 判斷是否是迴文字串 res = s2; } } } j++; } } return res; } public boolean isPalindrome(String s) { boolean b = true; for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { b = false; } } return b; } };
解法二:
這種解法同樣可以通過Lintcode的測試,但無法通過LeetCode……
/** * * 對於每個子串的中心(可以是一個字元,或者是兩個字元的間隙,比如串abc,中心可以是a,b,c,或者是ab的間隙,bc的間隙)往兩邊同時進行掃描, * 直到不是迴文串為止。假設字串的長度為n,那麼中心的個數為2*n-1(字元作為中心有n個,間隙有n-1個)。 * 對於每個中心往兩邊掃描的複雜度為O(n),所以時間複雜度為O((2*n-1)*n)=O(n^2),空間複雜度為O(1),程式碼如下: */ public class Solution { public String longestPalindrome(String s) { // write your code here String res = ""; if (s == null || s.length() == 0) { return ""; } int maxLen = 0; for (int i = 0; i < 2 * s.length() - 1; i++) { int left = i / 2; int right = i / 2; if (i % 2 == 1) { right++; } String str = lengthOfPalindrome(s, left, right); if (maxLen < str.length()) { maxLen = str.length(); res = str; } } return res; } public String lengthOfPalindrome(String s, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { left--; right++; } return s.substring(left + 1, right); } }
解法三:
此解法來自九章演算法,可以通過Lintcode和LeetCode的測試。
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
int length = s.length();
int max = 0;
String result = "";
for (int i = 1; i <= 2 * length - 1; i++) { // 2*length-1箇中心
int count = 1;
while (i - count >= 0 && i + count <= 2 * length && get(s, i - count) == get(s, i + count)) {
// i-count:左邊界。 i+count:右邊界
count++;
}
count--; // there will be one extra count for the outbound #
if (count > max) {
result = s.substring((i - count) / 2, (i + count) / 2); // 迴文子串
max = count;
}
}
return result;
}
private char get(String s, int i) {
if (i % 2 == 0) { // i是偶數,表示這個中心為間隙
return '#';
} else { // i是奇數,表明中心是字元
return s.charAt(i / 2);
}
}
}