码迷,mamicode.com
首页 > 编程语言 > 详细

python数据结构之字符串查找两例

时间:2016-05-11 11:30:31      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

查找字符串中最长连续数字子串

 问题描述

 查找给定字符串中最长的数字字串,返回其起始下标,长度和字串.例如:

 input  :abc12345cd123ef234567df

 output:15 6  234567

    实现

'''
查找给定字符串中最长的数字字串,返回其起始下标,长度和字串.例如:
input  :abc12345cd123ef234567df
output:15 6 234567
'''
def find_max_length_str(string):
    str_length = len(string)
    i = 0
    max_length = 0
    num_length = 0
    start_num = 0
    while i < str_length:
        if string[i] > '0' and string[i] < '9':
            start_num = i
            num_length = 0
            while i < str_length and string[i] > '0' and string[i] < '9':
                i += 1
                num_length += 1
            if num_length != 0 and max_length <= num_length:
                max_length = num_length
        i += 1
    return start_num, num_length, string[start_num:start_num + num_length]

 只需遍历一遍字符串,时间复杂度:O(n)

查找数字字符串中最长连续相同数字字串

 问题描述

查找给定数字串中最长连续相同字串,返回其起始下标,长度和子串.例如
input:11233344555666666
output:11 6 666666

 实现

'''
找到数字串中最长连续字串,返回其起始下标,长度和子串
input  :11233344555666666
output:11 6 666666
'''
def find_same_sequence_num(string):
    str_length = len(string)
    i = 0
    max_length = 0
    start_num = 0
    num_length = 0
    while i < str_length:
        if i + 1 < str_length and string[i] == string[i + 1]:
            start_num = i
            num_length = 1
            while i + 1 < str_length and string[i] == string[i + 1]:
                i += 1
                num_length += 1
            if num_length != 0 and max_length <= num_length:
                max_length = num_length
        i += 1
    return start_num, num_length, string[start_num:start_num + num_length]

    同样只需遍历一遍字符串,时间复杂度为O(n)

python数据结构之字符串查找两例

标签:

原文地址:http://blog.csdn.net/shuaijiasanshao/article/details/51371896

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!