Leetcode: Longest Substring with At Most Two Distinct Characters
2015-11-04 05:58
423 查看
Question
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.For example, Given s = “eceba”,
T is “ece” which its length is 3.
Hide Company Tags Google
Hide Tags Hash Table Two Pointers String
Hide Similar Problems
Solution
Get idea from here1, here2Using sliding window method
[code]class Solution(object): def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ s = list(s) start, res = 0,0 dict_c = {} for cur,c in enumerate(s): if c in dict_c: dict_c[c] += 1 else: # new char while len(dict_c.keys())>1: # make sure there is only one char in the window before c if dict_c[ s[start] ]==1: del dict_c[ s[start] ] else: dict_c[ s[start] ] -= 1 start += 1 dict_c[c] = 1 res = max(res, cur-start+1) # have to update res no matter what happens return res
相关文章推荐
- 正则表达式入门
- Xcode 警告信息处理:Format string is not a string literal (potentially insecure)
- android80 HttpClient框架提交数据 get方式
- Odoo 库存管理-库存移动(Stock Move)新玩法
- odoo8.0+PyCharm4.5开发环境配置
- LC - Bulls and Cows
- iOS 如何进行逆向工程?
- c++ read
- [CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组
- UIView的Touch事件UIControlEvents详解
- JS学习笔记(03)——(联动菜单,计时器)
- [IOS]绑定事件时,为何看不到具体的UIControlEvents对象,只有事件委托?
- Android笔记(五十一) 短信验证码集成——mob平台
- JAVA多线程之常用方法
- C# 制作软件启动画面
- 使用mysql yum包安装mysql5.5
- 第一天CSS实战培训及笔记及感想
- LeetCode Serialize and Deserialize Binary Tree
- [2020]:绝对值排序
- Leetcode #23 Merge k Sorted Lists