时间复杂度O(N)
string="35534321"
def max_substr(string):
s_list=[s for s in string]
str1='#'+'#'.join(s_list)+'#'
length=len(str1)
max=0
for i in range(length):
sum=get_length(str1,i)
if(sum>max):
max=sum
return max
def get_length(string,index):
length=len(string)
r1=0
print(index)
for i in range(1,index+1):
if (index+i<length) and (string[index-i]==string[index+i]):
r1+=1
else:
break
return r1
print(max_substr(string))
var s = 'cfffafffaabaa'
var arr = []
var result = [0]
for (let i = 0; i < s.length; i++) {
arr.push('#')
arr.push(s[i])
}
arr.push('#')
var c = 0
for (let i = 1; i < arr.length; i++) {
while ((i - c >= 0) && (i + c < arr.length) && arr[i - c] === arr[i + c]) {
c++
}
result.push(c)
c = 0
}
console.log(`最大回文长度: ${Math.max.apply(null, result) - 1}`)
var center = (result.indexOf(Math.max.apply(null, result)) - 1) / 2
var range = (Math.max.apply(null, result)) / 2 - 1
console.log("最大回文:" + s.substring(center - range, center + range + 1))
网友评论