Longest Palindromic Substring 解法
第三周题目
难度:Media
LeetCode题号:5
题目
Description:
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”
思考
此次考虑二重循环
第一重,从字符串最左边开始向右循环扫描(循环变量i,递增)
第二重,从字符串最右边开始向左扫描(循环变量j,递减)
(这里注意,当 j-i+1 <= 最长子字符串长度时跳出二重循环)当遇到两个字符相同时,提取子字符串x
判断x是否是回文字符串,如果是,则跳出二重循环(因为j继续递减并不会出现更长的子字符串)
代码
class Solution {
public:
string longestPalindrome(string s) {
int max_len = 1;
string max_str = "";
for (int i = 0; i < s.length(); i++) {
for (int j = s.length()-1; j-i+1 > max_len; j--) {
if (s[i] == s[j]) {
string sub = s.substr(i, j-i+1);
if (IsPalin(sub)) {
if (sub.length() > max_len) {
max_str = sub;
max_len = sub.length();
break;
}
}
}
}
}
string result = "";
result += s[0];
return max_str.length()>0 ? max_str:result;
}
bool IsPalin(string s) {
int i = 0, j = s.length() - 1;
while (s[i] == s[j] && i < j) {
i++;
j--;
}
return i>=j ? true:false;
}
};