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.
//给每个字符串都找一个中心对称点,然后从中心对称点向两边扩散找最大长度的子串 //预处理,使每个字符串都有一个中心对称点,例如:abcba -> #a#b#c#b#a# abba -> #a#b#b#a# public String preProcess(String s){ if(s.length() == 0) return"#"; String result = ""; for(int i = 0; i < s.length(); i++) { result += "#" + s.charAt(i); } result += "#"; return result; }
public String longestPalindrome(String s){
if(s.length() == 1){ return s; } s = preProcess(s); int maxs = 1, L = 0, R = 0; //枚举中心对称点 for(int i = 0; i < s.length(); i++){ int left = i - 1; int right = i + 1; int len = 1; while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){ len += 2; if(len > maxs){ maxs = len; L = left;//记录最长的回文串的边界 R = right; } left--; right++; } }
StringBuilder sb = new StringBuilder(); for(int i = L; i < R; i++){ if(s.charAt(i) != '#') sb.append(s.charAt(i)); } return sb.toString(); }