5. Longest Palindromic Substring
method: 2 pointers starting in the middle
1 set 2 pointers l, r, starting from middle to left and right side
2 if get the longest, stop and iterate next.
3 there are 2 cases for starting points: same points or joint points
Python:
class Solution:
def longestPalindrome(self, s: str) -> str:
def helper(l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1: r]
res = ""
for i in range(len(s)):
test = helper(i, i)
if len(test) > len(res): res = test
test = helper(i, i+1)
if len(test) > len(res): res = test
return res
647. Palindromic Substrings
Change a litter from above, helper is used to count the numbers, the total number:odd numbers + even numbers of substrings
class Solution:
def countSubstrings(self, s: str) -> int:
# count the number of palindrome starting from l, r
def helper(l, r):
count = 0
while l >= 0 and r < len(s) and s[l] == s[r]:
count += 1
l -= 1
r += 1
return count
res = 0
for i in range(len(s)):
res += helper(i, i)
res += helper(i, i+1)
return res