Skip to content

Commit a55e1e6

Browse files
committed
Longest Palindromic Substring
1 parent 85abd8d commit a55e1e6

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

Diff for: DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
- [Check if strings are rotations of each other or not](https://practice.geeksforgeeks.org/problems/check-if-strings-are-rotations-of-each-other-or-not-1587115620/1# "view question") - [Cpp Solution](./solutions/Check%20if%20strings%20are%20rotations%20of%20each%20other%20or%20not.cpp)
6363
- [Program to Check if a string is a valid shuffle of two distinct strings](https://www.programiz.com/java-programming/examples/check-valid-shuffle-of-strings "view topic")
6464
- [Count and Say](https://leetcode.com/problems/count-and-say/ "view question") - [Cpp Solution](./solutions/Count%20and%20Say.cpp)
65+
- [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/ "view question") - [Cpp Solution](./solutions/Longest%20Palindromic%20Substring.cpp)
6566
- []( "view question") - [Cpp Solution](./solutions/.cpp)
6667

6768
### Searching & Sorting
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Longest Palindromic Substring
3+
=============================
4+
5+
Given a string s, return the longest palindromic substring in s.
6+
7+
Example 1:
8+
Input: s = "babad"
9+
Output: "bab"
10+
Note: "aba" is also a valid answer.
11+
12+
Example 2:
13+
Input: s = "cbbd"
14+
Output: "bb"
15+
16+
Example 3:
17+
Input: s = "a"
18+
Output: "a"
19+
20+
Example 4:
21+
Input: s = "ac"
22+
Output: "a"
23+
24+
Constraints:
25+
1 <= s.length <= 1000
26+
s consist of only digits and English letters (lower-case and/or upper-case),
27+
*/
28+
29+
string longestPalindrome(string s)
30+
{
31+
int n = s.size(), max_len = 1;
32+
string ans = s.substr(0, 1);
33+
vector<vector<int>> dp(n, vector<int>(n, 0));
34+
35+
for (int i = 0; i < n; ++i)
36+
dp[i][i] = 1;
37+
for (int i = 0; i + 1 < n; ++i)
38+
{
39+
if (s[i] == s[i + 1])
40+
{
41+
max_len = 2;
42+
ans = s.substr(i, 2);
43+
dp[i][i + 1] = 1;
44+
}
45+
}
46+
47+
for (int gap = 2; gap < n; ++gap)
48+
{
49+
for (int i = 0; i + gap < n; ++i)
50+
{
51+
int j = i + gap;
52+
if (s[i] == s[j] && dp[i + 1][j - 1])
53+
{
54+
if (max_len < gap + 1)
55+
{
56+
max_len = gap + 1;
57+
ans = s.substr(i, gap + 1);
58+
}
59+
dp[i][j] = 1;
60+
}
61+
}
62+
}
63+
64+
return ans;
65+
}

0 commit comments

Comments
 (0)