Skip to content

Commit

Permalink
[python]longest-palindromic-substring
Browse files Browse the repository at this point in the history
  • Loading branch information
Huauauaa committed Aug 26, 2024
1 parent 4009964 commit 60c82e3
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/leetcode/00005.longest-palindromic-substring/5-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
def longestPalindrome(self, s: str) -> str:
res = s[0]
for i in range(len(s)):
for j in range(i + 1, len(s)):
if j - i + 1 > len(res) and self.check(s, i, j):
res = s[i : j + 1]
return res

def check(self, s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True


if __name__ == "__main__":
print(Solution().longestPalindrome("babad"))
print(Solution().longestPalindrome("cbbd"))
30 changes: 30 additions & 0 deletions src/leetcode/00005.longest-palindromic-substring/5-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution:
"""
## P(i,j)
1. i == j => true
2. j - i <= 2 => s[i] == s[j]
3. j -i > 2=> s[i] == s[j] && P(i+1,j-1)
"""

def longestPalindrome(self, s: str) -> str:
res = s[0]
length = len(s)
arr = [[False for _ in range(length)] for _ in range(length)]
for i in range(len(s) - 1, -1, -1):
for j in range(i + 1, len(s)):
if i == j:
arr[i][j] = True
elif j - i <= 2:
arr[i][j] = s[i] == s[j]
else:
arr[i][j] = (s[i] == s[j]) and arr[i + 1][j - 1]
if arr[i][j] and j - i + 1 > len(res):
res = s[i : j + 1]
return res


if __name__ == "__main__":
# print(Solution().longestPalindrome("babad"))
# print(Solution().longestPalindrome("cbbd"))
print(Solution().longestPalindrome("abcba"))
23 changes: 23 additions & 0 deletions src/leetcode/00005.longest-palindromic-substring/5-3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution:
def __init__(self):
self.res = ""

def longestPalindrome(self, s: str) -> str:
self.res = s[0]

for i in range(len(s)):
self.work(s, i, i)
self.work(s, i, i + 1)
return self.res

def work(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
if right - left - 1 > len(self.res):
self.res = s[left + 1 : right]


if __name__ == "__main__":
print(Solution().longestPalindrome("babad"))
print(Solution().longestPalindrome("cbbd"))

0 comments on commit 60c82e3

Please sign in to comment.