问题描述:
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)。首先从字符串的开头位置一直往后遍历,在每次遍历的过程中由该位置向两边扩散,直到找到最长的子回文串为止。同时需要考虑奇字符串和偶字符串的情况。
代码如下:
public class Solution {
public String longestPalindrome(String s) {
int n = s.length();
String longest = s.substring(0, 1); if (s == null || s.length() == 0)
return null;
for (int i = 0; i < n; i++) {
String p1 = expandFromCenter(s, i, i);
if (p1.length() > longest.length())
longest = p1;
String p2 = expandFromCenter(s, i, i + 1);
if (p2.length() > longest.length())
longest = p2;
}
return longest;
} public String expandFromCenter(String s, int c1, int c2) {
int head = c1;
int tail = c2;
int m = s.length(); while (head >= 0 && tail < m && s.charAt(head) == s.charAt(tail)) {
head--;
tail++;
}
return s.substring(head + 1, tail);
}
}