Fork me on GitHub

leetcode——[005]Longest Palindromic Substring最长回文子串

题目

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

1
2
3
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

示例 2:

1
2
输入: "cbbd"
输出: "bb"

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

1
2
3
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

1
2
Input: "cbbd"
Output: "bb"

解题方法

动态规划、中心扩展法。回文串长度可能是奇数也可能是偶数,以所有最简单的单字符回文串(一个字符,e.g. “a”)和双字符回文串(两个字符,e.g. “aa”)为中心,向两边展开,展开的字符相等且新回文串长度大于之前最大回文串长度,则更新最大回文串。这段代码跑了16ms,超过了90.89%的Java提交。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution
// Method 2 16ms 90.89%
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i); // single char as center
int len2 = expandAroundCenter(s, i, i + 1); // double chars as center
int len = Math.max(len1, len2);
if (len > end - start) { // update start and end
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
}
BJTU-HXS wechat
海内存知己,天涯若比邻。