Python实现简单查找最长子串功能示例

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 print

Longest 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
# 如果只有一个字符，也返回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最长公共子串和最长公共子序列的实现 