算法题总结-最长回文序列
原题
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1?tpId=37&tqId=21255&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=3&judgeStatus=undefined&tags=&title=
Catcher是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
输入描述:
输入一个字符串(字符串的长度不超过2500)
输出描述:
返回有效密码串的最大长度
输入示例
12HHHHA
输出示例
4
最长回文序列解题思路:
从中心点出发,逐个比对两侧字符是否相同[从短到长]
注意事项;
1、判别需注意奇数与偶数两种判别,奇数的初始化长度为1,偶数初始化长度为2
import sys
count = 0
data = ""
for line in sys.stdin:
a = line.split()
if count > 0:
break
if count==0:
data = a[0]
pass
count += 1
def oddJudge(string:str,index:int)->int:
out = 1
length = len(string)
for subLen in range(1,length):
if (index-subLen)>=0 and (index+subLen)<=(length-1):
a = string[index-subLen]
b = string[index+subLen]
if a==b:
out+=2
else:
break
pass
return out
def evenJudge(string:str,index:int)->int:
out = 2
length = len(string)
for subLen in range(1,length):
if (index-subLen)>=0 and (index+1+subLen)<=(length-1):
a = string[index - subLen]
b = string[index + 1 + subLen]
if a==b:
out+=2
else:
break
pass
return out
dictionary = [0]
length = len(data)
outLen = [0]
for i in range(1,length-1):
# 逐个字符进行中心点判别
# 奇数判别
oddTmp = oddJudge(data,i)
# 偶数判别
evenTmp = 0
if data[i]==data[i+1]:
evenTmp = evenJudge(data,i)
pass
outLen.append(max(oddTmp,evenTmp))
pass
maxValue = max(outLen)
maxIndex = outLen.index(maxValue)
print(maxValue)