From 11d708b69bb2d37f2c8d3b99441d7e060002edac Mon Sep 17 00:00:00 2001 From: enril <48513933+enrilwang@users.noreply.github.com> Date: Sat, 20 Mar 2021 19:55:00 +1100 Subject: [PATCH 1/2] =?UTF-8?q?Update=20=E6=9C=80=E9=95=BF=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=90=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 高频面试系列/最长回文子串.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/高频面试系列/最长回文子串.md b/高频面试系列/最长回文子串.md index 5873277..030257b 100644 --- a/高频面试系列/最长回文子串.md +++ b/高频面试系列/最长回文子串.md @@ -167,4 +167,38 @@ class Solution { } ``` + +[enrilwang](https://github.com/enrilwang) 提供 Python 代码: + +```python +// 中心扩展算法 +class Solution: + def longestPalindrome(self, s: str) -> str: + //用n来装字符串长度,res来装答案 + n = len(s) + res = str() + //字符串长度小于2,就返回本身 + if n < 2: return s + for i in range(n-1): + //oddstr是以i为中心的最长回文子串 + oddstr = self.centerExtend(s,i,i) + //evenstr是以i和i+1为中心的最长回文子串 + evenstr = self.centerExtend(s,i,i+1) + temp = oddstr if len(oddstr)>len(evenstr) else evenstr + if len(temp)>len(res):res=temp + + return res + + def centerExtend(self,s:str,left,right)->str: + // + while left >= 0 and right < len(s) and s[left] == s[right]: + left -= 1 + right += 1 + //这里要注意,跳出while循环时,恰好s[left] != s[right] + return s[left+1:right] + + +``` + + 做完这题,大家可以去看看 [647. 回文子串](https://leetcode-cn.com/problems/palindromic-substrings/) ,也是类似的题目 From d83128b78dc217854758ca576495e6b6390e605e Mon Sep 17 00:00:00 2001 From: enril <48513933+enrilwang@users.noreply.github.com> Date: Sat, 20 Mar 2021 20:13:39 +1100 Subject: [PATCH 2/2] =?UTF-8?q?Update=20=E6=9C=80=E9=95=BF=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=90=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 高频面试系列/最长回文子串.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/高频面试系列/最长回文子串.md b/高频面试系列/最长回文子串.md index 030257b..7aa5748 100644 --- a/高频面试系列/最长回文子串.md +++ b/高频面试系列/最长回文子串.md @@ -171,18 +171,18 @@ class Solution { [enrilwang](https://github.com/enrilwang) 提供 Python 代码: ```python -// 中心扩展算法 +# 中心扩展算法 class Solution: def longestPalindrome(self, s: str) -> str: - //用n来装字符串长度,res来装答案 + #用n来装字符串长度,res来装答案 n = len(s) res = str() - //字符串长度小于2,就返回本身 + #字符串长度小于2,就返回本身 if n < 2: return s for i in range(n-1): - //oddstr是以i为中心的最长回文子串 + #oddstr是以i为中心的最长回文子串 oddstr = self.centerExtend(s,i,i) - //evenstr是以i和i+1为中心的最长回文子串 + #evenstr是以i和i+1为中心的最长回文子串 evenstr = self.centerExtend(s,i,i+1) temp = oddstr if len(oddstr)>len(evenstr) else evenstr if len(temp)>len(res):res=temp @@ -190,11 +190,11 @@ class Solution: return res def centerExtend(self,s:str,left,right)->str: - // + while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 - //这里要注意,跳出while循环时,恰好s[left] != s[right] + #这里要注意,跳出while循环时,恰好s[left] != s[right] return s[left+1:right]