标签:
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(n^2)。
public String longestPalindrome(String s) { if(s == null || s.length() == 0) return ""; String ret = ""; int len = s.length(); for(int i=0; i<len; i++) { String tmp1 = helper(s, i, i+1); String tmp2 = helper(s, i-1, i+1); String tmp = tmp1.length() > tmp2.length() ? tmp1 : tmp2; ret = ret.length() > tmp.length() ? ret : tmp; } return ret; } public String helper(String s, int left, int right) { int len = s.length(); while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)) { left--; right++; } return s.substring(left+1, right); }
思路二:Manacher算法,时间复杂度为O(n)。
具体算法思想可以参考:
http://blog.csdn.net/insistgogo/article/details/12287805
http://blog.csdn.net/pi9nc/article/details/9251455
public String longestPalindromeII(String s) { if(s == null || s.length() == 0) return ""; StringBuilder sb = new StringBuilder(); sb.append(‘s‘).append(‘#‘); for(int i=0; i<s.length(); i++) sb.append(s.charAt(i)).append(‘#‘); String newStr = sb.toString(); int[] p = new int[sb.length()]; manacher(newStr, p); int idx = 0; for(int i=1; i<p.length; i++) idx = p[i] > p[idx] ? i : idx; return newStr.substring(idx - p[idx], idx + p[idx] + 1).replace("#", ""); } public void manacher(String s, int[] p) { int id = 1; int mx = 1; for(int i=1; i<s.length(); i++) { if(mx > i) p[i] = Math.min(mx - i, p[(id<<1) - i]); else p[i] = 0; while(i+p[i]+1 < s.length() && i-p[i]-1 > 0 && s.charAt(i+p[i]+1) == s.charAt(i-p[i]-1)) p[i]++; if(i + p[i] > mx) { id = i; mx = i + p[i]; } } }
标签:
原文地址:http://www.cnblogs.com/ivanyangzhi/p/4733040.html