-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5.最长回文子串.cpp
46 lines (43 loc) · 918 Bytes
/
5.最长回文子串.cpp
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
/*
* @lc app=leetcode.cn id=5 lang=cpp
*
* [5] 最长回文子串
*/
#include <iostream>
#include <string>
using namespace std;
// @lc code=start
class Solution
{
public:
string longestPalindrome(string s)
{
if (s.size() == 1)
return s;
string res = "";
for (int i = 0; i < s.size(); i++)
{
string ol = palindrome(s, i, i);
string oh = palindrome(s, i, i + 1);
res = res.size() > ol.size() ? res : ol;
res = res.size() > oh.size() ? res : oh;
}
return res;
}
string palindrome(string s, int l, int h)
{
while (l >= 0 && h < s.size() && s[l] == s[h])
{
l--;
h++;
}
return s.substr(l + 1, h - l - 1);
}
};
// @lc code=end
int main()
{
Solution s;
string str = "babad";
cout << s.longestPalindrome(str) << endl;
}