描述
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”
难度:medium
这道题简单来说找到一个字符串最长的“回文”字符串
思路
说是medium的题,但是貌似很多easy的题都比他难了,一开始我还想着有一些特别的算法。其实maximum length才1000,就用最naive的方法就可以了。。
将整个字符串遍历一遍,以每个字符为中心向两边搜索,然后找到最长的结果就行了,然后再考虑一下结果长度是奇数还是偶数的情况就ok了
答案
class Solution {
private:
int l, r;
public:
Solution() {
l = 0;
r = 0;
}
string longestPalindrome(string s) {
if (s.length() < 2) {
return s;
}
for (int i = 0; i < s.length(); ++i) {
this->findLongest(s, i, i);
this->findLongest(s, i, i + 1);
}
return s.substr(l, r - l + 1);
}
inline void findLongest(string & s, int left, int right) {
if (s[left] != s[right])
return;
while (left > 0 && right < s.length() - 1) {
--left;
++right;
if (s[left] != s[right]) {
++left;
--right;
break;
}
}
if (right - left > r - l) {
r = right;
l = left;
}
}
};