Python实现简单查找最长子串功能示例
本文实例讲述了Python实现简单查找最长子串功能。分享给大家供大家参考,具体如下:
题目选自edX公开课MITx:6.00.1xIntroductiontoComputerScienceandProgramming课程Week2的ProblemSet1的第三题。下面是原题内容。
Assume s isastringoflowercasecharacters.
Writeaprogramthatprintsthelongestsubstringof s inwhichthelettersoccurinalphabeticalorder.Forexample,ifs='azcbobobegghakl',thenyourprogramshouldprint
Longestsubstringinalphabeticalorderis:beggh
Inthecaseofties,printthefirstsubstring.Forexample,if s='abcbcd',thenyourprogramshouldprintLongestsubstringinalphabeticalorderis:abc
Forproblemssuchasthese,donotinclude raw_input statementsordefinethevariable s inanyway.Ourautomatedtestingwillprovideavalueof s foryou-sothecodeyousubmitinthefollowingboxshouldassume s isalreadydefined.Ifyouareconfusedbythisinstruction,pleasereviewL4Problems10and11beforeyoubeginthisproblemset.
代码如下:
#-*-coding:utf-8-*-
#!python2
#判断一个字符串内的字母是否是按字母表顺序
#如IsStrIncre('abbcdg')返回True
#IsStrIncre('abbadg')返回False
#如果只有一个字符,也返回False
defIsStrIncre(s):
forcntinrange(len(s)-1):
iflen(s)==1:
returnFalse
elifs[cnt]>s[cnt+1]:
returnFalse
returnTrue
s='abajsiesnwdw'#examplecode
substr=''
forlengthinrange(1,len(s)+1):
firstflag=True#aflagtorememberthefirststringthatsatisfiedtherequirements
#andignorethestringssatisfiedtherequirementsbutappearedafter
forcntinrange(len(s)-length+1):
ifIsStrIncre(s[cnt:cnt+length]):
iffirstflag:
substr=s[cnt:cnt+length]
firstflag=False
print'Longestsubstringinalphabeticalorderis:'+substr
运行结果:
Longestsubstringinalphabeticalorderis:ajs
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。