forked from saadfareed/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
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 in java and python (saadfareed#50)
* Regular Expression Matching * Longest palindromic substring in python * Longest_palidrom_Substring in Python * Longest_Palindromic_Substring in java
- Loading branch information
1 parent
b347ab5
commit 7565626
Showing
2 changed files
with
48 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,25 @@ | ||
public class Longest_Palindromic_Substring { | ||
private int lo, maxLen; | ||
public String longestPalindrome(String s) { | ||
int len = s.length(); | ||
if (len < 2) | ||
return s; | ||
|
||
for (int i = 0; i < len-1; i++) { | ||
extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible | ||
extendPalindrome(s, i, i+1); //assume even length. | ||
} | ||
return s.substring(lo, lo + maxLen); | ||
} | ||
|
||
private void extendPalindrome(String s, int j, int k) { | ||
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) { | ||
j--; | ||
k++; | ||
} | ||
if (maxLen < k - j - 1) { | ||
lo = j + 1; | ||
maxLen = k - j - 1; | ||
} | ||
} | ||
} |
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,23 @@ | ||
class Solution: | ||
def longestPalindrome(self, s: str) -> str: | ||
longest_palindrom = '' | ||
dp = [[0]*len(s) for _ in range(len(s))] | ||
#filling out the diagonal by 1 | ||
for i in range(len(s)): | ||
dp[i][i] = True | ||
longest_palindrom = s[i] | ||
|
||
# filling the dp table | ||
for i in range(len(s)-1,-1,-1): | ||
# j starts from the i location : to only work on the upper side of the diagonal | ||
for j in range(i+1,len(s)): | ||
if s[i] == s[j]: #if the chars mathces | ||
# if len slicied sub_string is just one letter if the characters are equal, we can say they are palindomr dp[i][j] =True | ||
#if the slicied sub_string is longer than 1, then we should check if the inner string is also palindrom (check dp[i+1][j-1] is True) | ||
if j-i ==1 or dp[i+1][j-1] is True: | ||
dp[i][j] = True | ||
# we also need to keep track of the maximum palindrom sequence | ||
if len(longest_palindrom) < len(s[i:j+1]): | ||
longest_palindrom = s[i:j+1] | ||
|
||
return longest_palindrom |