题目
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
#
#
# 输出: "bab"
# 注意: "aba" 也是一个有效答案。
#
#
#
# 输出: "bb"
#
# Related Topics 字符串 动态规划
# 👍 2604 👎 0
解题思路
python实现
class Solution(object):
"""
计算最大回文字符串
"""
def run(self, data):
"""
中心扩展
O(n^2)
:param data:
:return:
"""
if not data:
return
result_point = dict()
result_nopoint = dict()
result = dict()
max_length_index = 0
for i in range(len(data)):
left_point = i
right_point = i
while left_point >= 0 and right_point < len(data) and data[left_point] == data[right_point]:
result_point[i] = data[left_point:right_point+1]
left_point -= 1
right_point += 1
left_point = i
right_point = i+1
while left_point >= 0 and right_point < len(data) and data[left_point] == data[right_point]:
result_nopoint[i] = data[left_point:right_point+1]
left_point -= 1
right_point += 1
if i in result_nopoint:
result[i] = result_point[i]
if len(result_point[i]) >= len(result_nopoint[i]):
result[i] = result_point[i]
else:
result[i] = result_nopoint[i]
else:
result[i] = result_point[i]
max_length_index = i if len(result[i]) > max_length_index else max_length_index
return result[max_length_index]
def windows(self):
"""
滑动窗口法
return
"""
def main():
data = "bcacccccca"
print Solution().run(data)
if __name__ == '__main__':
main()