Skip to content

Commit e8e1e34

Browse files
authored
solution for longest palindromic subsequence
1 parent 52a3977 commit e8e1e34

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution
2+
{
3+
public:
4+
int check(string &s, int L, int R)
5+
{
6+
while (L >= 0 and R < s.length() and s[L] == s[R])
7+
{
8+
L--;
9+
R++;
10+
}
11+
return R - L - 1;
12+
}
13+
14+
string longestPalindrome(string s)
15+
{
16+
17+
int ans = 0, st = 0;
18+
int n = s.length();
19+
20+
for (int i = 0; i < n; i++)
21+
{
22+
int len1 = check(s, i, i);
23+
int len2 = check(s, i, i + 1);
24+
25+
int len = max(len1, len2);
26+
27+
if (len > ans)
28+
{
29+
ans = len;
30+
st = i - (len - 1) / 2;
31+
}
32+
}
33+
return s.substr(st, ans);
34+
}
35+
};

0 commit comments

Comments
 (0)