Skip to content

Commit 82727f3

Browse files
committed
Solution as on 27-06-2022 07:00 am
1 parent d548e4e commit 82727f3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// 5.✅ Longest Palindromic Substring
2+
3+
class Solution
4+
{
5+
public:
6+
string longestPalindrome(string s)
7+
{
8+
int n = s.size();
9+
vector<vector<int>> t(n, vector<int>(n, 0));
10+
11+
string ans;
12+
int maxlen = 0;
13+
14+
for (int diff = 0; diff < n; ++diff)
15+
{
16+
for (int i = 0, j = i + diff; j < n; ++i, ++j)
17+
{
18+
if (i == j)
19+
t[i][j] = 1;
20+
else if (diff == 1)
21+
t[i][j] = (s[i] == s[j]) ? 2 : 0;
22+
else
23+
{
24+
if (s[i] == s[j] && t[i + 1][j - 1])
25+
t[i][j] = t[i + 1][j - 1] + 2;
26+
}
27+
if (t[i][j])
28+
{
29+
if (j - i + 1 > maxlen)
30+
{
31+
maxlen = j - i + 1;
32+
ans = s.substr(i, maxlen);
33+
}
34+
}
35+
}
36+
}
37+
return ans;
38+
}
39+
};

0 commit comments

Comments
 (0)