栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

查找N个唯一字符的最长子串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

查找N个唯一字符的最长子串

有一个O(n)。让

S
是字符串。刚去通过阵列有两个指针
i
j
并跟踪数
K
之间不同的字母
S[i]
S[j]
。增量
j
每当这个数小于或等于
n
和增量
i
每当
K
大于
n
。还要记住最长的子字符串
K
等于
n

在实现中,您还需要一个哈希表来跟踪字母的最后一次出现。

Python实现:

def longest(S,n):    i = j = K = 0    res = (0,0)    last = {}    while i < len(S):        # if current substring is better than others than save        if K == n and j - i > res[1] - res[0]: res = (i,j)        # if we reach the end of the string, we're done.        if j + 1 > len(S): break        # if we can go further with the right end than do it        elif K <= n and j + 1 <= len(S): if not last.has_key(S[j]):     K = K + 1 last[S[j]] = j j = j + 1        # if we must go further with the left end than do it        else: if last.has_key(S[i]):     del last[S[i]]     K = K - 1 i = i + 1    return S[res[0]:res[1]]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号