給定一個字符串 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 )