标签:
查找给定字符串中最长的数字字串,返回其起始下标,长度和字串.例如:
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 ''' 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]
标签:
原文地址:http://blog.csdn.net/shuaijiasanshao/article/details/51371896