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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

django 发送手机验证码的示例代码

django 发送手机验证码的示例代码

一、流程分析: 1.用户在项目前端,输入手机号,然后点击【获取验证码】,将手机号发到post到后台。 2.后台验证手机号是否合法,是否已被占用,如果通过验证,则生成验证码,并通过运行脚本...

pyqt5 实现多窗口跳转的方法

今天在做pyqt5的多页面跳转时遇到问题,一点击button按钮,程序会崩溃。在网上查了下,应该是当窗口A调用窗口B的时候,两个窗口不能是同一类型。我写的时候把A、B同时写成了QWidg...

KMP算法精解及其Python版的代码示例

KMP算法是经典的字符串匹配算法,解决从字符串S,查找模式字符串M的问题。算法名称来源于发明者Knuth,Morris,Pratt。 假定从字符串S中查找M,S的长度ls,M的长度lm,...

TF-IDF与余弦相似性的应用(一) 自动提取关键词

TF-IDF与余弦相似性的应用(一) 自动提取关键词

TF-IDF与余弦相似性的应用(一):自动提取关键词 这个标题看上去好像很复杂,其实我要谈的是一个很简单的问题。 有一篇很长的文章,我要用计算机提取它的关键词(Automatic Key...

Python及Django框架生成二维码的方法分析

本文实例讲述了Python及Django框架生成二维码的方法。分享给大家供大家参考,具体如下: 一、包的安装和简单使用 1.1 用Python来生成二维码很简单,可以看 qrcode 这...