Python實現(xiàn)簡單查找最長子串功能示例
本文實例講述了Python實現(xiàn)簡單查找最長子串功能。分享給大家供大家參考,具體如下:
題目選自edX公開課 MITx: 6.00.1x Introduction to Computer Science and Programming 課程 Week2 的Problem Set 1的第三題。下面是原題內容。
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, ifs = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should printLongest substring in alphabetical order is: abc
For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 before you begin this problem set.
代碼如下:
# -*- coding:utf-8 -*-
#! python2
#判斷一個字符串內的字母是否是按字母表順序
# 如IsStrIncre('abbcdg') 返回 True
# IsStrIncre('abbadg') 返回 False
# 如果只有一個字符,也返回False
def IsStrIncre(s):
for cnt in range(len(s) - 1):
if len(s) == 1:
return False
elif s[cnt] > s[cnt+1]:
return False
return True
s = 'abajsiesnwdw'# example code
substr = ''
for length in range(1, len(s)+1):
firstflag = True # a flag to remember the first string that satisfied the requirements
# and ignore the strings satisfied the requirements but appeared after
for cnt in range(len(s)-length+1):
if IsStrIncre(s[cnt: cnt+length]):
if firstflag:
substr = s[cnt: cnt+length]
firstflag = False
print 'Longest substring in alphabetical order is: ' + substr
運行結果:
Longest substring in alphabetical order is: ajs
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結構與算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python調用SMTP服務自動發(fā)送Email的實現(xiàn)步驟
這篇文章主要介紹了Python調用SMTP服務自動發(fā)送Email的實現(xiàn)步驟,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-02-02
python使用pygame實現(xiàn)笑臉乒乓球彈珠球游戲
這篇文章主要為大家詳細介紹了python使用pygame實現(xiàn)笑臉乒乓球彈珠球游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
關于np.meshgrid函數(shù)中的indexing參數(shù)問題
Meshgrid函數(shù)在二維與三維空間中用于生成坐標網(wǎng)格,便于進行圖像處理和空間數(shù)據(jù)分析,二維情況下,默認使用笛卡爾坐標系,而三維meshgrid則涉及不同的坐標軸取法,在三維情況下,可能會出現(xiàn)坐標軸排列序混亂2024-09-09
面向新手解析python Beautiful Soup基本用法
這篇文章主要介紹了面向新手解析python Beautiful Soup基本用法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07

