---
# System prepended metadata

title: 5. Longest Palindromic Substring

---

# 5. Longest Palindromic Substring

https://leetcode.com/problems/longest-palindromic-substring/

###### Medium

##### Solution
```python=
class Solution:
    def longestPalindrome(self, s: str) -> str:
        
        lps = ''
        n = len(s)

        for i in range(n):
            odd = self.findPalindrome(s,i,i)
            even = self.findPalindrome(s,i,i+1)

            if len(odd) > len(lps):
                lps = odd

            if len(even) > len(lps):
                lps = even

        return lps

    def findPalindrome(self,s:str,l:int,r:int):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        
        return s[l+1:r]
```

##### Note
用中心擴展方式推斷迴文
bab -> 奇數判斷,以a為中心
bbaabb -> 偶數判斷,以aa為中心

