【题目描述】:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
【我的思路】:
从string前部开始,从长到短依次查找最长回文字符串,若找到一个,则从前部下一个字符开始继续寻找下一个回文串(不需要再找同一个前部下标开始的回文串了,长度不可能再增加)。
但是这个思路又超时惹(:з」∠)。
【我的代码】:
Submission Result: Time Limit Exceeded_(:з」∠)_。
待看大神代码…
class Solution {
public:
string longestPalindrome(string s) {
int maxPalindromicLen = 0;
int front = -1;
int end = -1;
int len = (int)s.size();
for (int i = 0; i < len; ++i) {
for (int j = len - 1; j >= 0; --j) {
if (isPalindromicString(s, i, j)) {
if (j - i + 1 > maxPalindromicLen) {
front = i;
end = j;
}
maxPalindromicLen = max(maxPalindromicLen, j - i + 1);
break;
}
}
}
return s.substr(front, maxPalindromicLen);
}
private:
bool isPalindromicString(string s, int front, int end) {
bool result = true;
while (front <= end) {
if (s.at(front) == s.at(end)) {
++front;
--end;
} else {
result = false;
break;
}
}
return result;
}
};