這個題目是昨天偶然又看到,考慮把它實現一下。
要求實現的結果如下:
給定字符串"abcabcbb",結果是長度為3的"abc";
給定字符串"bbbbb",結果是長度為1的"b";
給定字符串"pwwkew",結果是長度為3的"wke"。注意一點:結果一定是子字符串,比如"pwke"是由子字符串拼接的字符串,不是子字符串。
要求已經給的很明確,也很容易理解,下面給您奉上小主的手稿:
1 from collections import Counter 2 3 4 def search_max_len_substring(string): 5 """ 6 給定一個字符串,查找最長子字符串(沒有重復字符)的長度。 7 :param string: 8 :return: 最長子字符串,最長子字符串的長度 9 """ 10 no_repeat_strings = [] 11 start_index = 0 12 end_index = 1 13 14 if not string: 15 print('空字符串') 16 return None, None 17 else: 18 while end_index <= len(string): 19 tmp_str = string[start_index : ] if end_index == len(string) else string[start_index : end_index] 20 counter_dict = Counter(tmp_str) 21 if 2 in list(counter_dict.values()): # 有重復字符 22 start_index += 1 23 else: # 沒有重復字符 24 no_repeat_strings.append([tmp_str, len(tmp_str)]) # 保存沒有重復字符的字符串 25 end_index += 1 26 27 no_repeat_strings.sort(key=lambda item: item[1], reverse=True) # 降序排列 28 target_str, target_str_len= no_repeat_strings[0][0], no_repeat_strings[0][1] 29 return target_str, target_str_len
函數多返回了一個值,即子字符串的長度。
(有不對的地方,您多多指正,大家互相學習)