forked from changqing16/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.cpp
More file actions
72 lines (68 loc) · 1.5 KB
/
5.cpp
File metadata and controls
72 lines (68 loc) · 1.5 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
string longestPalindrome(string s)
{
int size = s.size();
if (size == 1)
return s;
char str[size];
strcpy(str, s.c_str());
int before, after, count, ans = 0;
int start;
bool flag;
for (int i = 1; i < size; i++)
{
count = 1;
if (str[i] == str[i - 1])
{
before = i - 2;
count = 2;
flag = true;
}
else
{
before = i - 1;
flag = false;
}
after = i + 1;
while (before >= 0 && after < size)
{
if (str[before] == str[after])
count += 2;
else
break;
if (flag && str[before + 1] != str[after])
flag = false;
before--;
after++;
}
if (flag && after < size && str[before + 1] == str[after])
{
after++;
count++;
while (before >= 0 && after < size)
{
if (str[before] == str[after])
count += 2;
else
break;
before--;
after++;
}
}
if (count > ans)
{
ans = count;
start = before + 1;
}
}
return s.substr(start, ans);
}
int main()
{
string s = "sssooosss";
string ans = longestPalindrome(s);
cout << ans << endl;
}