-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Longest palindromic Substring Code Added
- Loading branch information
1 parent
cd312d0
commit d633401
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Longest Palindromic Substring - LeetCode Problem 5 | ||
// https://leetcode.com/problems/longest-palindromic-substring/ | ||
|
||
class Solution | ||
{ | ||
public: | ||
string longestPalindrome(string s) | ||
{ | ||
int n = s.size(); | ||
int start; | ||
int length; | ||
vector<vector<int>> dp(n, vector<int>(n, 0)); | ||
for (int gap = 0; gap < n; gap++) | ||
{ | ||
for (int i = 0, j = gap; j < n; i++, j++) | ||
{ | ||
if (gap == 0) | ||
{ | ||
dp[i][j] = 1; | ||
} | ||
else if (gap == 1) | ||
{ | ||
if (s[i] == s[j]) | ||
{ | ||
dp[i][j] = 2; | ||
} | ||
} | ||
else | ||
{ | ||
if (s[i] == s[j] && dp[i + 1][j - 1] > 0) | ||
{ | ||
dp[i][j] = 2 + dp[i + 1][j - 1]; | ||
} | ||
} | ||
if (dp[i][j] > 0) | ||
{ | ||
start = i; | ||
length = dp[i][j]; | ||
} | ||
} | ||
} | ||
return s.substr(start, length); | ||
} | ||
}; |