Week4:Longest Palindromic Substring
Difficulty:Medium
1.Question
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.
Input: “cbbd”
Output: “bb”
2.Algorithm
使用动态规划求解:
P(i,j)=true,如果字符串"Si…Sj"是回文子串;否则为false
P(i,j)=(P(i+1,j−1)andSi==Sj)
上式最终会变成P(i,i)=true或P(i,i+1)=(Si==Si+1)
3.Solution
class Solution {
public:
string longestPalindrome(string s) {
int start = 0;
int maxLength = 0;
for(int i = 0; i < s.length(); i++) {
//以i为中心,返回长度必定为奇数
int len1 = maxAroundCenter(s,i,i);
//以i和i+1为中心,返回长度必定为偶数
int len2 = maxAroundCenter(s,i,i+1);
//以i为中心的最大回文子串长度
int len = 0;
if(len1 < len2 ) {
len = len2;
}
else {
len = len1;
}
if(maxLength < len) {
maxLength = len;
start = i - (len-1) / 2;
}
}
return s.substr(start,maxLength);
}
int maxAroundCenter(string s, int left, int right) {
while(left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
};