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.
自己的解决方案;
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上会报超时错误。
参考讨论区的解答
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; } } }
时间: 2024-11-11 03:05:13