题目
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) {
}
};
思路
遍历字母,以每一个字母为中心,同时遍历前后相对应的字母,判断是否相等。如果不相等则停止遍历。但是这样只能找出aba这样的,找不出abba,abbbba这样的,所以在前面先用两个while循环将所有与中心相同的字母包含进来。
代码
class Solution {
public:
string longestPalindrome(string s) {
int size = s.size();
if (size <= 1) {
return s;
}
int start = 0, max = 1;
for (int i = 1; i < size; i++) {
int start_ = i-1, end_ = i+1;
int current = 1;
while (start_ >= 0 && s[start_] == s[i]) {//忽略所有相同的字母,如aaa,aa
start_--;
current++;
}
while (end_ <= size && s[end_] == s[i]) {//忽略相同字母
end_++;
current++;
}
while (start_ >= 0 && end_ >= 0) {
if (s[start_] == s[end_]) {
start_--;
end_++;
current += 2;
} else {
start_++;
break;
}
}
if (start_ < 0) {//避免aa这样的字符串使start_小于0
start_++;
}
if (current > max) {
max = current;
start = start_;
}
}
return s.substr(start, max);
}
};