-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestPalidromicString.cpp
More file actions
75 lines (72 loc) · 2.04 KB
/
Copy pathlongestPalidromicString.cpp
File metadata and controls
75 lines (72 loc) · 2.04 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
73
74
75
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
string naiveApproach(string s)
{
string rev = s;
reverse(rev.begin(), rev.end());
int n = s.size();
int len = 0;
string ans;
for (int i = 0; i < n; ++i)
{
for (int j = 1; j <= n - i; ++j)
{
string t1 = s.substr(i, j);
string t2 = rev.substr(n - j - i, j);
cout << t1 << " " << t2 << "\n";
if (t1 == t2 && len < j)
{
len = j;
ans = t1;
}
}
}
return ans;
}
string longestPalindrome(string s)
{
pair<int, int> index;
int n = s.size();
for (int i = 0; i < n; i++)
{
int left = i, right = i + 1;
while (left >= 0 && right < n)
{
if (s[left] != s[right])
{
if (index.second - index.first < right - left - 2)
index = {left + 1, right - 1};
break;
}
left--, right++;
if (left < 0 || right >= n)
if (index.second - index.first < right - left - 2)
index = {left + 1, right - 1};
}
left = i, right = i;
while (left >= 0 && right < n)
{
if (s[left] != s[right])
{
if (index.second - index.first < right - left - 2)
index = {left + 1, right - 1};
break;
}
left--, right++;
if (left < 0 || right >= n)
if (index.second - index.first < right - left - 2)
index = {left + 1, right - 1};
}
}
return s.substr(index.first, index.second - index.first + 1);
}
};
int main()
{
string s;
cin >> s;
cout << Solution().longestPalindrome(s);
}