给定一个字符串 s 和正整数 n,
请使用你熟悉的编程语言输出 s 中包含不超过 n 种字符的最长子串,
如 s="uabbcadbaef",n=4 时应该输出 "abbcadba"。
# 判断一个字符串里面有几个不同字目
def count_diff(s):
arr = []
for i in s:
if i not in arr:
arr.append(i)
return len(arr)
# 获得最长子串
def get_longest_str( s, n ):
res_temp = ''
length = len(s)
for i in range(length-n):
for j in range(i,length):
str_temp = s[i:j]
if count_diff( str_temp )<=n and len(str_temp)>len(res_temp):
res_temp = str_temp
return res_temp
if __name__ == '__main__':
s = "uabbcadbaef"
n = 4
res = get_longest_str( s,n )
print( res )