Leetcode 5. Longest Palindromic Substring

https://leetcode.com/problems/longest-palindromic-substring/

题意:搜索一个字符串中最长的回文序列

思路:回文序列的搜索以中间一个单独一个字母和中间两个相同字符分为两类

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
string longestPalindrome(string s) {
if(s.length() == 1){
return s;
}
int left = 0, right = 0, index = 0, len = 0, wide = 0, res_index = 0;
for(int i = 0; i < s.length()-1; i++){
if(s[i] == s[i+1]){
index = searchPalindrome(s, i, i+1, len);
if(len > wide){
wide = len;
res_index = index;
}
}

index = searchPalindrome(s, i, i, len);

if(len > wide){
wide = len;
res_index = index;
}
}

return s.substr(res_index, wide);
}

int searchPalindrome(string s, int left, int right, int &len){
int index = 0;
int flag = 0;
while(left > 0 && right < s.length()-1){
left -= 1;
right += 1;
if(s[left] != s[right]){
flag = 1;
break;
}
}
if(flag == 1){
len = right - left - 1;
index = left + 1;
}
else{
len = right - left + 1;
index = left;
}
return index;
}
};

0%