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

这篇文章介绍了如何使用Python解决一个字符串中字母按字母表顺序排列的最长子串查找问题。通过示例代码和IsStrIncre函数,展示了如何找到并打印符合条件的最长子串。适用于初学者理解Python数据结构和算法的应用。
摘要由CSDN通过智能技术生成

本文实例讲述了python实现简单查找最长子串功能。分享给大家供大家参考,具体如下:

题目选自edX公开课 MITx: 6.00.1x Introduction to Computer Science and Programming 课程 Week2 的Problem Set 1的第三题。下面是原题内容。

Assumesis a string of lower case characters.

Write a program that prints the longest substring ofsin 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, ifs = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc

For problems such as these, do not includeraw_inputstatements or define the variablesin any way. Our automated testing will provide a value ofsfor you - so the code you submit in the following box should assumesis 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数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值