-
Notifications
You must be signed in to change notification settings - Fork 64
/
Solution.cpp
47 lines (41 loc) · 994 Bytes
/
Solution.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
47
class Solution
{
public:
std::string longestPalindrome(std::string s)
{
if (s.length() <= 1)
{
return s;
}
int max_len = 1;
std::string max_str = s.substr(0, 1);
for (int i = 0; i < s.length(); ++i)
{
for (int j = i + max_len; j <= s.length(); ++j)
{
if (j - i > max_len && isPalindrome(s.substr(i, j - i)))
{
max_len = j - i;
max_str = s.substr(i, j - i);
}
}
}
return max_str;
}
private:
bool isPalindrome(const std::string &str)
{
int left = 0;
int right = str.length() - 1;
while (left < right)
{
if (str[left] != str[right])
{
return false;
}
++left;
--right;
}
return true;
}
};