Longest Palindromic Substring2015年6月20日

时间:2025-01-23 14:33:44
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is , and there exists one unique longest palindromic substring.

自己的解决方案;

public class Solution {
StringBuilder longest = new StringBuilder(""); public String longestPalindrome(String s) {
String ss;
int len = s.length();
int max = 0;
int sublen = 0;
String result = "";
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
ss = s.substring(i, j);
int index = s.indexOf(reverse(ss),j-1);
if (index == j - 1) {
sublen = 2 * (j - 1 - i) + 1;
if (sublen > max) {
max = sublen;
result = s.substring(i, max+i);
}
continue;
} else if (index == j) {
sublen = 2 * (j - i);
if (sublen > max) {
max = sublen;
result = s.substring(i, max+i);
}
continue;
} else {
continue;
}
}
} return result;
} public String reverse(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
}

方法正确性是没有问题的,先挨个取子串,查找反串。但在LeetCode上会报超时错误。

参考讨论区的解答

Runtime: 344 ms

在所有JAVA程序里相对靠前

public class Solution {
StringBuilder longest = new StringBuilder(""); public String longestPalindrome(String s) {
if (s.length() <= 1) return s; for (int i = 0; i < s.length(); i++) {
expand(s, longest, i, i); //odd
expand(s, longest, i, i + 1); //even
} return longest.toString();
} private void expand(String s, StringBuilder longest, int i, int j) {
while (i >= 0 && j < s.length()) {
if (s.charAt(i) == s.charAt(j)) {
if (j - i + 1 > longest.length()) {
longest.delete(0, longest.length());
longest.append(s.substring(i, j + 1));
}
i--;
j++;
}
else
break;
}
}
}

代码剖析:

以字符串basdsa为例:

b a s d s a

i=:

odd对应的while循环执行
i=,j=
if (s.charAt(i) == s.charAt(j)) 满足 longest=b
even对应的while循环不满足 if (s.charAt(i) == s.charAt(j))条件break i=: odd对应的while循环执行
i=,j=
if (j - i + > longest.length()) 不满足
i=,j= if (s.charAt(i) == s.charAt(j)) 不满足循环退出
even对应的while循环不满足 if (s.charAt(i) == s.charAt(j))条件break i=: odd对应的while循环执行
i=, j=
if (j - i + > longest.length()) 不满足
i=,j= if (s.charAt(i) == s.charAt(j)) 不满足循环退出
even对应的while循环不满足 if (s.charAt(i) == s.charAt(j))条件break i=: odd对应的while循环执行
i=, j=
if (j - i + > longest.length()) 不满足
i=,j= if (s.charAt(i) == s.charAt(j)) 满足 longest=sds
i=,j= if (s.charAt(i) == s.charAt(j)) 满足 longest=asdsa
i=,j=6不满足while条件退出
even对应的while循环不满足 if (s.charAt(i) == s.charAt(j))条件break i=: odd对应的while循环执行
i=, j=
if (j - i + > longest.length()) 不满足
i=,j= if (s.charAt(i) == s.charAt(j)) 不满足循环退出
even对应的while循环不满足 if (s.charAt(i) == s.charAt(j))条件break i=: odd对应的while循环执行
i=, j=
if (j - i + > longest.length()) 不满足
i=, j=6不满足while条件退出
even对应的while不满足while条件退出