欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-08-27 10:58:15
本文实例讲述了python实现简单查找最长子串功能。分享给大家供大家参考,具体如下: 题目选自edx公开课 mitx: 6.00.1x introduction to c...

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

题目选自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 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
# 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程序设计有所帮助。