给定一个字符串 s 和正整数 n,
请使用你熟悉的编程语言输出 s 中包含不超过 n 种字符的最长子串,
如 s="uabbcadbaef",n=4 时应该输出 "abbcadba"。
1 # 判断一个字符串里面有几个不同字目
2 def count_diff(s):
3 arr = []
4 for i in s:
5 if i not in arr:
6 arr.append(i)
7 return len(arr)
8
9 # 获得最长子串
10 def get_longest_str( s, n ):
11 res_temp = ''
12 length = len(s)
13 for i in range(length-n):
14 for j in range(i,length):
15 str_temp = s[i:j]
16 if count_diff( str_temp )<=n and len(str_temp)>len(res_temp):
17 res_temp = str_temp
18 return res_temp
19
20 if __name__ == '__main__':
21 s = "uabbcadbaef"
22 n = 4
23 res = get_longest_str( s,n )
24 print( res )