查找字符串中最长连续数字子串
问题描述
查找给定字符串中最长的数字字串,返回其起始下标,长度和字串.例如:
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)
时间: 2024-10-11 23:36:19