# 5. Longest Palindromic Substring 暴力 800ms -> dp 97ms -> 回归原始 3ms AC

114人阅读 评论(0)

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

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.


Example:

Input: "cbbd"

Output: "bb"


class Solution {
public:
string longestPalindrome(string s) {
int maxL = 0, rl = 0, rr = 0;
int n = s.size();
for(int i = 0; i < s.size(); i++){
for(int j = n - 1; j >=i; j--){
int left = i, right = j;
while(left <= right){
if(s[left] == s[right]){
left++;
right--;
}else{
break;
}

}
if(right < left){
if(maxL < j - i + 1){
maxL = j - i + 1;
rl = i;
rr = j;
break;
}
}
if(maxL >= n - i - 1) break;
}
}
return s.substr(rl, rr - rl + 1);
}
};

public class Solution {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0) {
return "";
}
int len = s.length();
boolean[][] dp = new boolean[len][len];
int start = 0;
int end = 0;
int max = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = 0; j <= i; j++) {
if(s.charAt(i) == s.charAt(j) && (i - j <= 2 || dp[j+1][i-1])) {
dp[j][i] = true;
}
if(dp[j][i] && max < i - j + 1) {
max = i - j + 1;
start = j;
end = i;
}
}
}
return s.substring(start, end + 1);
}
}

class Solution {
public:
std::string longestPalindrome(std::string s) {
if (s.size() < 2)
return s;
int len = s.size(), max_left = 0, max_len = 1, left, right;
for (int start = 0; start < len && len - start > max_len / 2;) {
left = right = start;
while (right < len - 1 && s[right + 1] == s[right])
++right;
start = right + 1;
while (right < len - 1 && left > 0 && s[right + 1] == s[left - 1]) {
++right;
--left;
}
if (max_len < right - left + 1) {
max_left = left;
max_len = right - left + 1;
}
}
return s.substr(max_left, max_len);
}
};

0
0

个人资料
• 访问：15304次
• 积分：1108
• 等级：
• 排名：千里之外
• 原创：99篇
• 转载：5篇
• 译文：0篇
• 评论：0条