# 5. Longest Palindromic Substring

XAMPP教程 42浏览

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

Example 1:

Output: “bab”
Note: “aba” is also a valid answer.
Example 2:

Input: “cbbd”
Output: “bb”

Runtime: 16 ms, faster than 75.08% of Java online submissions for Longest Palindromic Substring.

class Solution {
// assume s must not be null or empty
public String longestPalindrome(String s) {
if (null == s || s.length() <= 1) {
return s;
}

int sLen = s.length();
// left, right, maxLeft, maxRight, maxLen
// 内部多个变量转成数组
int[] metrics = {0, 0, 0, 0, 0};
for (int i = 0; i < sLen; i++) {
// even
metrics[0] = i – 1;
metrics[1] = i;
longestPalindrome(metrics, s);
// odd
metrics[0] = i – 1;
metrics[1] = i + 1;
longestPalindrome(metrics, s);
}

return s.substring(metrics[2], metrics[3] + 1);
}
// 私有方法
private static void longestPalindrome(int[] metrics, String s) {
while (metrics[0] >= 0 && metrics[1] < s.length()
&& s.charAt(metrics[0]) == s.charAt(metrics[1])) {
metrics[0]–;
metrics[1]++;
}
int curLen = metrics[1] – metrics[0] – 1;
if (curLen > metrics[4]) {
metrics[4] = curLen;
metrics[2] = metrics[0] + 1;
metrics[3] = metrics[1] – 1;
}
}
}

Runtime: 59 ms, faster than 40.22% of Java online submissions for Longest Palindromic Substring.

class Solution {
// assume s must not be null or empty
public String longestPalindrome(String s) {
if (null == s || s.length() < 1) {
return s;
}
int sLen = s.length(), maxLen = 1;
String result = s.substring(0, 1);
for (int i = 0; i < sLen; i++) {
// even
int left = i – 1, right = i;
while (left >= 0 && right < sLen && s.charAt(left) == s.charAt(right)) {
left–;
right++;
}
if (right – left – 1 > maxLen) {
maxLen = right – left – 1;
result = s.substring(left + 1, right); // 构造字符串开销，可以用变量记录开始与结束下标
}

// odd
left = i – 1;
right = i + 1;
while (left >= 0 && right < sLen && s.charAt(left) == s.charAt(right)) {
left–;
right++;
}
if (right – left – 1 > maxLen) {
maxLen = right – left – 1;
result = s.substring(left + 1, right);
}
}
return result;
}
}