LeetCode-5. Longest Palindromic Substring(M)
解法
比较经典的问题,寻找最长回文子串。Leetcode里提供了多种解法。我采用最直观的解法:中心扩展法。
思路是每次以当前元素为中心向两边扩展,直到遇到不同元素,此时找到一个子串。有两点需要注意的地方:
1)空串和单字符都是回文,直接返回即可。
2)偶数回文和奇数回文的情况。例如:abace是aba的奇数串,以b为中心向两周扩展即可。但是abbawe是偶数串abba,这样需要以bb为指针向两周同时往外扩展。
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
class Solution: def longestPalindrome(self, s: str) -> str: # 空串和长度为1的字串本身就是回文子串 if len(s)<=1: return s temp = "" for i in range(len(s)-1): #i为当前字符,遍历整个字串 # left i right i means current char left = right = i #奇数回文串情况 while(left>=0) and (right<len(s)) and (s[left] == s[right]): #奇数回文串,所以k j指针指向i两边的元素 left,right = left-1, right+1 temp1 = s[left+1:right] # if else简洁写法,类似3目运算符 temp = temp1 if len(temp1) > len(temp) else temp if(s[i] == s[i+1]): left,right = i,i+1 # 重点在while的用法,不断的循环,直到找到第一个不满足条件的位置跳出 while(left>=0) and (right < len(s)) and (s[left] == s[right]): left,right = left-1, right+1 #因为这行紧挨着while,说明刚好不满足条件,
#满足条件left = left+1, right = right + 1, 因为Python是左闭右开的区间,所以right不用-1 temp1 = s[left+1:right] temp = temp1 if len(temp1) > len(temp) else temp return temp