代码拉取完成,页面将自动刷新
#coding:UTF-8
'''
range 是作闭有开
- 首先判断是否是符合条件的字符串
- 如果不是,则进行查找,如果是,那直接返回
- 从出入变量的中间开始进行遍历,一种是找奇数类型的回文,一种是偶数类的回文
'''
def isRevertString(s):
s_length = len(s)
for i in range(0,(s_length/2)+1):
if s[i] !=s[s_length-1-i]:
return False
return True
'''
method feature:从中间的字母算开始,看是否是回文
parameters:
s:输入的字符串
middle:开始的中心位置
max_walk_setps_forword:从中心位置到 s 末尾的距离
以 s="abdba"为例,middle=2,max_walk_setps_forword=2
以 s="abddba"为例,middle=3,max_walk_setps_forword=2
还有问题:
1.无论是奇数还是偶数,最短的回文都有可能是奇数或者偶数回文组成的
2.还有可能找到奇数、偶数都行的,这时候就需要比较一下了,此函数返回的就是一个字典了
'''
def isRevertStringFromMinddle(s , middle , max_walk_setps_forword):
result = {"qishu":0,"oushu":0}
if 1 == len(s):
result["qishu"] = 1
return result
else:
huiwenFlag = 0
for index in range(1 , max_walk_setps_forword):
if s[middle - index] != s[middle+index]:
break
huiwenFlag = huiwenFlag +1;
if max_walk_setps_forword == huiwenFlag :
result["qishu"] = middle
huiwenFlag = 0
for i in range(0 , max_walk_setps_forword):
if s[ middle - i ] != s[ middle + 1 +i ]:
break
huiwenFlag = huiwenFlag +1;
if max_walk_setps_forword == huiwenFlag :
result["oushu"] = middle
return result
'''
method feature: 利用 s 中间的位置来进行最短回文的拼接
parameter:
'''
def completeRevertString(s , middle):
end = len(s) - 2*(len(s) - middle-1)
for i in range(0 , end):
s = s + s[end - 1 -i]
return s
s = "abddfadsfasf"
if not isRevertString(s):
mid = len(s)/2
s_hafl_len = mid +1
targetMiddle = 0
r = {}
for i in range(0,mid-( 0 if 0 == len(s)%2 else 1)):
#print len(s) - mid -i
targetMiddle = mid + i
r = isRevertStringFromMinddle(s, mid + i, mid - i - ( 1 if 0 == len(s)%2 else 0))
if 0 == (r["oushu"] | r["qishu"]):
continue
else:
break
if len(s) == (1+targetMiddle):
print completeRevertString(s, targetMiddle)
elif 1 == r["oushu"]:
print completeRevertString(s, targetMiddle )
elif 1==r["qishu"]:
print completeRevertString(s, targetMiddle )
elif 1 == (r["oushu"] & r["qishu"]):
if(len(completeRevertString(s, r["oushu"] )) > len(completeRevertString(s, r["qishu"] ))):
print completeRevertString(s, r["oushu"] )
else:
print completeRevertString(s, r["qishu"] )
else:
print "%s is a revert string"%s
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。