需求: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.
如果一个字符串从左向右写和从右向左写是一样的,这样的字符串就叫做palindromic string
判断回文数,中间开花。定一个中心,向两边散开。这个中心是从左到右移动的。需要2个游标。
int palindrome(String ps,int left,int right) 这个方法用来判断回文字段,返回字段长度
String longestPalindrome(String s) 在这里调用palindrome方法,遍历字符串去找。遍历过程注意不要越界。
以下为Java代码:
/** * @author Rust Fisher * @date 2015-9-14 */ public class LongestPalindromicSubstring { /** * @param s - input string * @return the Longest Palindromic Substring */ public static String longestPalindrome(String s) { String result = ""; int inputLenght = s.length(); int startIndex = 0; int longest = 1; for (int i = 0; i < inputLenght; i++) { int oddLen = 1,dualLen = 1, currentLen; oddLen = palindrome(s, i, i); if (i+1 < inputLenght) { dualLen = palindrome(s, i, i+1); } currentLen = dualLen > oddLen ? dualLen : oddLen; if (currentLen > longest){ longest = currentLen; if (longest%2 == 0) { startIndex = i - longest/2 + 1; } else { startIndex = i - longest/2; } } } for (int i = startIndex; i < startIndex+longest; i++) { result += s.charAt(i); } return result; } /** * @param ps - input string * @param left - index move left * @param right - index move right * @return the current length of palindrome */ public static int palindrome(String ps,int left,int right){ int thislen = 0; int len = ps.length(); while(left >= 0 && right < len && ps.charAt(left) == ps.charAt(right)){ left--; right++; } thislen = right - left - 1; return thislen; } public static void main(String args[]){ System.out.println(longestPalindrome("hfiwafhaabbaaccddio128213")); System.out.println(longestPalindrome("abcdefgfedcba")); System.out.println(longestPalindrome("abc")); } }
输出:
aabbaa
abcdefgfedcba
a