标签:int length ilow maxlen 第五 maxpos 回文
第一思路 先写个判断回文的函数
def judge(list1): print(list1[0:0]) low = 0 high = len(list1)-1 if high <= 0: return True while low < high: if list1[low] == list1[high]: low += 1 high -= 1 else: break if low <high or list1[low] != list1[high]: return False else: return True
然后以每个字母为头去判断回文长度
发现根本不靠谱 因为有的短的不是回文 长的却是 这时间复杂度上天了
下面这个是错的
def long(s): length = 1 maxlen = 1 for i,each in enumerate(s): while i+length < len(s): if judge(s[i:i+length]) : length += 1 else: break if length-1 > maxlen: maxlen = length-1 length = 1 return maxlen print(long('aba'))
后面想着以每个回文中心作为判断依据
但是要注意 中心可能在两个字母中间 所以有了以下的代码
:
def judge2(s): i = 0 high = len(s)-1 maxlen = 0 maxpos = 0 while i <= high: if i % 1 == 0: i = int(i) j = 0 while (i-j)>=0 and (i+j)<=high: if s[i-j] == s[i+j]: length = 1+j*2 else: break if length > maxlen: maxpos = int(i) maxlen = length j += 1 else: j = 0 ilow = int(i//1) while (ilow-j)>=0 and (ilow+1+j)<=high: if s[ilow-j] == s[ilow+1+j]: length = j*2+2 else: break if length > maxlen: maxpos = int(ilow) maxlen = length j += 1 i = i +0.5 maxpos = int(maxpos) maxlen = int(maxlen) if maxlen %2 == 0: return s[maxpos-maxlen//2+1:maxpos+maxlen//2+1] else: return s[maxpos-maxlen//2:maxpos+maxlen//2+1]
每次步进0.5往后便历
如果不是整数 说明这一步在判断偶数个字母组成的回文.
标签:int,length,ilow,maxlen,第五,maxpos,回文 来源: https://www.cnblogs.com/xiaoli1996/p/15076137.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。