python代码
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
maxlength = 0
maxstr = ""
if len(s) == 1:
return s
for i in range(len(s)):
left = i
right = i
if maxlength > (len(s) - i + 1) * 2 - 1:
break
while right < len(s) - 1 and s[right] == s[right + 1]:
right += 1
while left - 1 >= 0 and right + 1 < len(s):
if s[left - 1] == s[right + 1]:
left = left - 1
right = right + 1
else:
break
if maxlength < right - left + 1:
if right == len(s) - 1:
maxstr = s[left:]
else:
maxstr = s[left:right + 1]
maxlength = right - left + 1
return maxstr
总结
1、方法思路:我们要寻找回文序列,由回文序列的性质可知,其分为两种:①“xxxAxxx”最中间为一个字符;②“xxxAAxxx”最中间为多个相同的字符。
因此,我们从最中间字符入手,遍历字符串的每一个字符,首先判断当前位置的字符是否能成为中间字符,若为中间字符,则通过指针指向其中间字符的两端,在移动的同时判断两端的字符是否相等,若不等则结束本轮循环,输出当前字符作为中间字符的最长回文子串。
考虑到当前字符对应的回文子串有可能是上述的②情况,所以当我们发现当前字符与其右侧字符相同时,则右指针右移一位,我们将多个相同的字符,作为中间字符。
2、细节上:
①字符串只有一个字符时,直接输出;
②若当前判断的字符其右侧的长度,不到已知最长回文子串的长度一半时,停止本轮循环。因为其不可能为最长,不必浪费时间。
③字符串转化为列表:
str1="abc123"
list1 = list(str1)
# 输出['a', 'b', 'c', '1', '2', '3']
④检查子字符串是否存在(in)
substring = "python"
string = "welcome to pythontip"
print(substring in string)
检查子字符串是否存在(string.find()),如果存在,则返回子字符串最左侧的索引,否则返回 -1(这意味着它不存在)
substring = "zz"
string = "hello world"
print(string.find(substring))
⑤从字符串创建子字符串列表
string = "welcome to pythontip"
print(string.split())
# 输出['welcome', 'to', 'pythontip']
⑥计算子字符串出现的次数
string = "we will have a quick coding lesson this afternoon"
print(string.count('noon'))
# 输出 1