Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
直接暴力解题了,首先,定义基准点i,偏移量j,对于回文子串根据长度奇偶来分有两种情况:
1、长度为奇数:s[i - j] == s[i + j];
2、长度为偶数:s[i - j] == s[i + j + 1];
时间复杂度为O(n2)
C++:
class Solution {
public:
string longestPalindrome(string s) {
string ret;
int i, j;
int len = 0;
for(i = 0; i < s.size(); i++) {
for(j = 0; i - j >= 0 && i + j < s.size(); j++) {
if(s[i - j] == s[i + j]) {
if(2 * j + 1 > len) {
len = 2 * j + 1;
ret = s.substr(i - j, len);
}
}
else break;
}
for(j = 0; i - j >= 0 && i + j + 1 < s.size(); j++) {
if(s[i - j] == s[i + j + 1]) {
if(2 * j + 2 > len) {
len = 2 * j + 2;
ret = s.substr(i - j, len);
}
}
else break;
}
}
return ret;
}
};
C:
char * longestPalindrome(char * s){
int i, j, n;
int len = 0;
int start = 0, end = 0;
for(i = 0; i < strlen(s); i++) {
for(j = 0; i - j >= 0 && i + j < strlen(s); j++) {
if(s[i - j] == s[i + j]) {
if(2 * j + 1 > len) {
len = 2 * j + 1;
start = i - j;
end = start + len;
}
}
else break;
}
for(j = 0; i - j >= 0 && i + j + 1 < strlen(s); j++) {
if(s[i - j] == s[i + j + 1]) {
if(2 + 2 * j > len) {
len = 2 + 2 * j;
start = i - j;
end = start + len;
}
}
else break;
}
}
s[end] = 0;
return s + start;
}