描述:
即在一个给定的或者用户键盘输入的字符串中输出一个长度最长的头尾相同的子字符串。
示例1:
输入:s = “babad” 输出:“bab”
解释:“aba” 同样是符合题意的答案。
方法1:暴力循环法
即遍历所有子串,判断每一个子串是否为回文串。
一:利用while循环遍历
def get_reverstring(string):
substring_length = len(string)
while substring_length > 0:
for i in range(len(string) - substring_length + 1):
temp = string[i: i + substring_length]
if temp == temp[::-1]:
return temp
substring_length -= 1
print (get_reverstring("buabfafbucbubwcaw"))
二:设立头尾两个游标遍历
def get_reverstring(str) -> str:
length = len(str)
max_substring = 0
if str == '' or length == 1:
return str
for i in range(length):
for j in range(length,i,-1):
if str[i:j] == str[i:j][::-1] and (j-1) > max_substring:
max_substring = (j-1)
temp_result_str = str[i:j]
break
return temp_result_str
print (get_reverstring("buabfafbucbubwcaw"))
>> bfafb
遍历子串的复杂度为O(n^2),判断是否为回文串为O(n),因此总时间复杂度为O(n^3)
方法2:中心扩散法
即把字符串分为单数和双数两种情况讨论,单数时则确定中心点向两边延伸,不匹配时跳出到下一个中心点进行判断,双数时则初始化left和right为i和i-1即可。
def get_reverstring(str):
length = len(str)
max_substring = 0
result = ''
if str =='' or length == 1:
return str
# 单数子串
for i in range(length):
left = right = i
while left >= 0 and right < length and str[left] == str[right]:
left -= 1
right += 1
if (right - left - 1) > max_substring:
max_substring = (right - left - 1)
result = str[left + 1:right]
# 双数子串
for i in range(length - 1):
left = i
right = i + 1
while left >= 0 and right < length and str[left] == str[right]:
left -= 1
right += 1
if (right - left - 1) > max_substring:
max_substring = (right - left - 1)
result = str[left + 1:right]
return result
print (get_reverstring("buabfafbucbubwcaw"))
>> bfafb
时间复杂度为O(n^2)。