Longest Substring with At Most K Distinct Characters

要点:要搞清楚At Most Two Distinct和Longest Substring Without Repeating Characters (No Repeating)的区别:前者的sliding window里只有2个char,但是可以任意重复。而后者可以有任意多个char但是任何char都不能有重复。

  • 所以解法上前者的hashset只有2个元素,而后者需要把所有distinct的元素放到hashset里。而前者因为只有当不在hashset中的元素才可能考虑更新hashset,而后者是有当前元素在hashset里更新。
  • 推广到k,
    • At Most K Distinct要把k个元素中最后一次出现(最右)最靠左的那个去掉,所以要不断更新最右边界,At Most K Repeating因为新元素在hashset中,所以去掉的只能是该元素,只是k扩展到要记录重复的元素个数是否到k才启动。
    • At Most K Distinct还有用count的方法:把集中检查边界分布到从左向右每个元素减少count,最先count减少到0的就是最左。而At Most K Repeating因为只去掉一个元素,没有这个方法。

要点:

  • 是对longest substring without repeating characters这题另一种思路的扩展。no repeating这题是用map存当前sliding window的字符,下一个char不能出现在map中。而distinct这题是下一个不能是没有在map中的(除非map中只有一个or <k个)。
  • k个中选哪个取代?显然k个字符中最后出现中最靠左的字符是所选。这样能保证当前sliding window中的local maxLen
  • 上面的方法每次新字符都要遍历k个在map中的字符,整体时间是O(n)*O(k)。另一种方法更类似no repeating的方法。直接从sliding window左边开始pop直到某个元素count==0(所以map中记录count)。其实也是找到最后出现的最靠左字符。

错误点:

  • start的更新在清楚左边界的loop内,如果没有进入这个清除环节,不需要更新start
  • start的更新在leftMost的+1位置
  • count version不用检查>0,因为在map中的都是如此
  • count version:注意start是index,umap[s[start]]
  • count version: 初始map中的count value是1而不是0
  • count version: 别忘了新元素进map(主要是光想着del key了)

https://repl.it/CaiH (map loop)
https://repl.it/CaiT/1 (k, count)
https://repl.it/CqmA (Two, use char1, char2 variables)

class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        n = len(s)
        maxLen = 0
        umap = {}
        start = 0
        for i in xrange(n):
            if s[i] not in umap and len(umap)>=k:
                leftMost = n
                rmChar = None
                for c in umap:
                    if umap[c]<leftMost:
                        leftMost = umap[c]
                        rmChar = c
                del umap[rmChar]
                start = leftMost+1 # error 1: start should be set inside update condition
                                   # error 2: start index: next of leftMost
            umap[s[i]]=i

            if i-start+1>maxLen:
                maxLen = i-start+1
            #print i,start,maxLen,umap
        return maxLen

sol = Solution()
print sol.lengthOfLongestSubstringKDistinct("aabbcc", 1)
print sol.lengthOfLongestSubstringKDistinct("aabbcc", 2)
print sol.lengthOfLongestSubstringKDistinct("aabbcc", 3)
print sol.lengthOfLongestSubstringKDistinct("eceba", 2)
        
# Given a string, find the length of the longest substring T that contains at most k distinct characters.

# For example, Given s = “eceba” and k = 2,

# T is "ece" which its length is 3.

# Hide Company Tags Google
# Hide Tags Hash Table String
# Hide Similar Problems (H) Longest Substring with At Most Two Distinct Characters

class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        umap = {}
        if k==0: return 0
        longest, start = 0,0
        for i in xrange(len(s)):
            # print "it=", i,umap,len(umap)
            if s[i] in umap:
                umap[s[i]]+=1
            elif len(umap)<k:
                umap[s[i]]=1 # error 1: should be 1, not 0
            else:
                umap[s[i]]=1 # error 2: don't forget to put myself into
                while start<i:
                    c = s[start]
                    start+=1
                    umap[c]-=1
                    if not umap[c]:
                        del umap[c]
                        break
            longest = max(longest, i-start+1)
        return longest

sol = Solution()
assert sol.lengthOfLongestSubstringKDistinct("eceba", 2)==3
        

边工作边刷题:70天一遍leetcode: day 71-1的更多相关文章

  1. 边工作边刷题:70天一遍leetcode: day 71

    Longest Substring with At Most Two Distinct Characters # Given a string, find the length of the long ...

  2. 边工作边刷题:70天一遍leetcode: day 89

    Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...

  3. 边工作边刷题:70天一遍leetcode: day 77

    Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...

  4. 边工作边刷题:70天一遍leetcode: day 78

    Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...

  5. 边工作边刷题:70天一遍leetcode: day 85-3

    Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...

  6. 边工作边刷题:70天一遍leetcode: day 101

    dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...

  7. 边工作边刷题:70天一遍leetcode: day 1

    (今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...

  8. 边工作边刷题:70天一遍leetcode: day 70

    Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...

  9. 边工作边刷题:70天一遍leetcode: day 71-3

    Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...

  10. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

随机推荐

  1. git 使用笔记(一)

    1. 环境介绍 windows10 2.使用 2.1 安装git for windows 2.2 创建一个文件夹, 开始git管理 2.3 查看该目录,包括隐藏文件 2.4 把testgit.txt添 ...

  2. C语言范例学习01

    编程语言的能力追求T型. 以前学过C语言,但是只学了理论. 从今天开始,我买了本<C语言程序开发范例宝典>.我要把它通关掉. 这应该可以极大地提升我的编程能力. 第一章 基础知识 这章没太 ...

  3. Couchbase介绍,更好的Cache系统

    在移动互联网时代,我们面对的是更多的客户端,更低的请求延迟,这当然需要对数据做大量的 Cache 以提高读写速度. 术语 节点:指集群里的一台服务器. 现有 Cache 系统的特点 目前业界使用得最多 ...

  4. S2 易买网总结

    易买网项目总结 --指导老师:原玉明 不知不觉,又到了S2结业的时间了,S1的项目KTV项目还历历在目.一路走来,感觉时间过的好快,我们离就业也越来越近... 展示: 1.主页面(首页) 01.商品分 ...

  5. Failed to install on device ‘emulator-5554′: timeout

    启动android模拟器时候如果提示:Failed to install on device ‘emulator-5554′: timeout 这是可能因为卡的原因导致启动超时,解决办法:eclips ...

  6. Java 上传文件到 SFTP 抛异常 java.lang.NoClassDefFoundError: Could not initialize class sun.security.ec.SunEC 的解决办法

    最近从 Op 那里报来一个问题,说是SFTP上传文件不成功.拿到的 Exception 如下: Caused by: java.lang.NoClassDefFoundError: Could not ...

  7. (四)play之yabe项目【页面】

    (四)play之yabe项目[页面] 博客分类: 框架@play framework   主页面 显示当前发表博客的完整内容,以及历史博客列表 Bootstrap Job 一个play job任务就是 ...

  8. 一个Chrome拓展——HttpPost

    周末花了点时间做了一个chrome拓展,叫HttpPost,顾名思义是用来测试http的post请求. 先直接看效果 插件与拓展 在说这个做的过程前,先说明什么是Chrome插件.Chrome拓展 1 ...

  9. SharePoint 2010 文档管理之点击次数

    前言:很多场景下,我们都需要对一篇文章或者文档的点击次数进行统计,然而SharePoint本身并没有给我们设计这样一个字段,所以我们需要通过简单的字段开发来实现这样一个功能. 一.创建项目: 1. 创 ...

  10. 实验12:Problem J: 动物爱好者

    #define null ""是用来将字符串清空的 #define none -1是用来当不存在这种动物时,返回-1. 其实这种做法有点多余,不过好理解一些. Home Web B ...