-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-palindromic-substring.cc
50 lines (46 loc) · 1.53 KB
/
longest-palindromic-substring.cc
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
50
#include "leetcode.h"
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
const char *chars = s.c_str();
switch (s.length()) {
case 0:
case 1: return s;
case 2: return chars[0] == chars[1] ? s : s.substr(0, 1);
default: {
int first = 0, max_len = 0, l = 0, r = 0;
for (size_t axis = 0; axis < s.length() - 1; ++axis) {
l = axis;
r = axis + 1;
while (l >= 0 && r < s.length() && chars[l] == chars[r]) {
--l;
++r;
}
if (r - l - 1 > max_len) {
first = l + 1;
max_len = r - l - 1;
}
if (axis > 0) {
l = axis - 1;
r = axis + 1;
while (l >= 0 && r < s.length() && chars[l] == chars[r]) {
--l;
++r;
}
if (r - l - 1 > max_len) {
first = l + 1;
max_len = r - l - 1;
}
}
}
return s.substr(first, max_len);
}
}
}
};
int main(int argc, char const *argv[]) {
Solution solution;
const string s = solution.longestPalindrome("babad");
cout << s << endl;
}