Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions C++/LongestPalindromicSubstring.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class Solution
{
string LCSubstr(string s1, string s2, vector<vector<int>> &t)
{
string ans = "";
int n = s1.size();
int mx = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (s1[i - 1] == s2[j - 1])
{
t[i][j] = 1 + t[i - 1][j - 1];
if (t[i][j] > mx)
{
// For every possible LC substring, we check whether it's a palindrome or not.
// We know the size of the LC substring, so using "i" and "t[i][j]" we can find the substring after that we just need to check whether it's palindrome or not.
string temp = s1.substr(i - t[i][j], t[i][j]);
string temp2(temp.rbegin(), temp.rend());

if (temp == temp2)
{
mx = t[i][j];
ans = temp;
}
}
}
else
{
t[i][j] = 0;
}
}
}

return ans;
}

public:
string longestPalindrome(string s1)
{
int n = s1.size();
vector<vector<int>> t(n + 1, vector<int>(n + 1, 0));
string s2(s1.rbegin(), s1.rend());
return LCSubstr(s1, s2, t);
}
};
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,8 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
| 070 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | [Java](./Java/climbing-stairs.java) | _O(N)_ | _O(1)_ | Easy | DP | |
| 730 | [Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences/) | [C++](./C++/Count-Different-Palindromic-Subsequences.cpp) | _O(N\*N)_ | _O(N\*N)_ | Hard | DP | |
| 55 | [Jump Game](https://leetcode.com/problems/jump-game/) | [Python](./Python/jumpGame.py) | _O(N)_ | _O(N)_ | Medium | DP | |
| 55 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | [C++](./C++/LonegstPalindromicSubstring) | _O(n^2)_ | _O(n^2)_ | Medium | DP | |


<br/>
<div align="right">
Expand Down