Skip to content

Commit

Permalink
Longest Palindromic Substring in java and python (saadfareed#50)
Browse files Browse the repository at this point in the history
* Regular Expression Matching

* Longest palindromic substring in python

* Longest_palidrom_Substring in Python

* Longest_Palindromic_Substring in java
  • Loading branch information
syedtalaljilani authored Oct 11, 2022
1 parent b347ab5 commit 7565626
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Java/Longest_Palindromic_Substring.java
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;
}
}
}
23 changes: 23 additions & 0 deletions Python/Longest_Palindromic_Substring.py
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

0 comments on commit 7565626

Please sign in to comment.