[LeetCode] Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.
Example 2:
Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.
这道题给我们一个字符串,让求最多有两个不同字符的最长子串。那么首先想到的是用 HashMap 来做,HashMap 记录每个字符的出现次数,然后如果 HashMap 中的映射数量超过两个的时候,这里需要删掉一个映射,比如此时 HashMap 中e有2个,c有1个,此时把b也存入了 HashMap,那么就有三对映射了,这时 left 是0,先从e开始,映射值减1,此时e还有1个,不删除,left 自增1。这时 HashMap 里还有三对映射,此时 left 是1,那么到c了,映射值减1,此时e映射为0,将e从 HashMap 中删除,left 自增1,然后更新结果为 i - left + 1,以此类推直至遍历完整个字符串,参见代码如下:
解法一:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = , left = ;
unordered_map<char, int> m;
for (int i = ; i < s.size(); ++i) {
++m[s[i]];
while (m.size() > ) {
if (--m[s[left]] == ) m.erase(s[left]);
++left;
}
res = max(res, i - left + );
}
return res;
}
};
我们除了用 HashMap 来映射字符出现的个数,还可以映射每个字符最新的坐标,比如题目中的例子 "eceba",遇到第一个e,映射其坐标0,遇到c,映射其坐标1,遇到第二个e时,映射其坐标2,当遇到b时,映射其坐标3,每次都判断当前 HashMap 中的映射数,如果大于2的时候,那么需要删掉一个映射,还是从 left=0 时开始向右找,看每个字符在 HashMap 中的映射值是否等于当前坐标 left,比如第一个e,HashMap 此时映射值为2,不等于 left 的0,那么 left 自增1,遇到c的时候,HashMap 中c的映射值是1,和此时的 left 相同,那么我们把c删掉,left 自增1,再更新结果,以此类推直至遍历完整个字符串,参见代码如下:
解法二:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = , left = ;
unordered_map<char, int> m;
for (int i = ; i < s.size(); ++i) {
m[s[i]] = i;
while (m.size() > ) {
if (m[s[left]] == left) m.erase(s[left]);
++left;
}
res = max(res, i - left + );
}
return res;
}
};
后来又在网上看到了一种解法,这种解法是维护一个 sliding window,指针 left 指向起始位置,right 指向 window 的最后一个位置,用于定位 left 的下一个跳转位置,思路如下:
1. 若当前字符和前一个字符相同,继续循环。
2. 若不同,看当前字符和 right 指的字符是否相同
(1) 若相同,left 不变,右边跳到 i - 1
(2) 若不同,更新结果,left 变为 right+1,right 变为 i - 1
最后需要注意在循环结束后,还要比较结果 res 和 s.size() - left 的大小,返回大的,这是由于如果字符串是 "ecebaaa",那么当 left=3 时,i=5,6 的时候,都是继续循环,当i加到7时,跳出了循环,而此时正确答案应为 "baaa" 这4个字符,而我们的结果 res 只更新到了 "ece" 这3个字符,所以最后要判断 s.size() - left 和结果 res 的大小。
另外需要说明的是这种解法仅适用于于不同字符数为2个的情况,如果为k个的话,还是需要用上面两种解法。
解法三:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int left = , right = -, res = ;
for (int i = ; i < s.size(); ++i) {
if (s[i] == s[i - ]) continue;
if (right >= && s[right] != s[i]) {
res = max(res, i - left);
left = right + ;
}
right = i - ;
}
return max(s.size() - left, res);
}
};
还有一种不使用 HashMap 的解法,是在做 Fruit Into Baskets 这道题的时候在论坛上看到的,其实这两道题除了背景设定之外没有任何的区别,代码基本上都可以拷来直接用的。这里使用若干的变量,其中 cur 为当前最长子串的长度,first 和 second 为当前候选子串中的两个不同的字符,cntLast 为 second 字符的连续长度。遍历所有字符,假如遇到的字符是 first 和 second 中的任意一个,那么 cur 可以自增1,否则 cntLast 自增1,因为若是新字符的话,默认已经将 first 字符淘汰了,此时候选字符串由 second 字符和这个新字符构成,所以当前长度是 cntLast+1。然后再来更新 cntLast,假如当前字符等于 second 的话,cntLast 自增1,否则均重置为1,因为 cntLast 统计的就是 second 字符的连续长度。然后再来判断若当前字符不等于 second,则此时 first 赋值为 second, second 赋值为新字符。最后不要忘了用 cur 来更新结果 res,参见代码如下:
解法四:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = , cur = , cntLast = ;
char first, second;
for (char c : s) {
cur = (c == first || c == second) ? cur + : cntLast + ;
cntLast = (c == second) ? cntLast + : ;
if (c != second) {
first = second; second = c;
}
res = max(res, cur);
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/159
类似题目:
Longest Substring Without Repeating Characters
Longest Substring with At Most K Distinct Characters
Subarrays with K Different Integers
参考资料:
https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串的更多相关文章
- [LeetCode] 159. Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串
Given a string s , find the length of the longest substring t that contains at most 2 distinct char ...
- [LeetCode] Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串
Given a string, find the length of the longest substring T that contains at most k distinct characte ...
- [LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串
Given a string, find the length of the longest substring T that contains at most k distinct characte ...
- 395 Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子串
找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k .输出 T 的长度.示例 1:输入:s = "aaabb", k = 3输出:3最 ...
- LeetCode Longest Substring with At Most Two Distinct Characters
原题链接在这里:https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ 题目: Gi ...
- LeetCode "Longest Substring with At Most K Distinct Characters"
A simple variation to "Longest Substring with At Most Two Distinct Characters". A typical ...
- [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串
Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...
- [leetcode]159. Longest Substring with At Most Two Distinct Characters至多包含两种字符的最长子串
Given a string s , find the length of the longest substring t that contains at most 2 distinct char ...
- Leetcode: Longest Substring with At Most K Distinct Characters && Summary: Window做法两种思路总结
Given a string, find the length of the longest substring T that contains at most k distinct characte ...
随机推荐
- WebGIS中快速整合管理多源矢量服务以及服务权限控制的一种设计思路
文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 在真实项目中,往往GIS服务数据源被其他多个信息中心或者第三方 ...
- MyCat源码分析系列之——SQL下发
更多MyCat源码分析,请戳MyCat源码分析系列 SQL下发 SQL下发指的是MyCat将解析并改造完成的SQL语句依次发送至相应的MySQL节点(datanode)的过程,该执行过程由NonBlo ...
- 类型“System.Data.Linq.DataContext”在未被引用的程序集中定义。必须添加对程序集“System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”的引用。
解决方法:添加System.Data.Linq.dll引用 http://www.cnblogs.com/m84641693/archive/2010/07/26/1785100.html http: ...
- 遭遇Web print
一直都知道Web打印还不太成熟,以前IE横行时,普遍都是采用打印相关的ActiveX控件,有些国产厂家做得不错,只是那时还没有付费能力,没有太多关注.而纯粹基于Web标准的打印,浏览器对CSS pri ...
- iframe关于滚动条的去除和保留
iframe嵌入页面后,我们有时需要调整滚动条,例如,去掉全部的滚动条,去掉右边的滚动条且保留底下的滚动条,去掉底下的滚动条且保留右边的滚动条.那么我们应该怎么做呢? 一:去掉全部的滚动条 第一个方法 ...
- Httpster –世界各地最潮的网页设计案例聚合网站
Httpster 这个网站聚合了世界各地最新最潮的网页设计案例,展示了创意的设计,精心的策划,优秀的排版.这些作品都按月份和类别进行了很好划分,你可以方便的找到自己感兴趣的网站案例. 立即去看看 您可 ...
- 使用tomcat manager 管理和部署项目
在部署tomcat项目的时候,除了把war文件直接拷贝到tomcat的webapp目录下,还有一种方法可以浏览器中管理和部署项目,那就是使用tomcat manager. 默认情况下,tomcat m ...
- SharePoint 2013 沙盒解决方案不能激活(激活按钮不可用)
把沙盒解决方案上传到目标站点的"解决方案"库中,发现"激活"按钮是灰掉的,不可用. 首先,我想到的是权限不足,所以 "以管理员身份"启动IE ...
- Looper.prepare()和Looper.loop()
什么时候需要 Looper Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建 ...
- 一步步学习 Spring Data 系列之JPA(一)
引入: Spring Data是SpringSource基金会下的一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得数据库的访问变得方便快捷,并支持map-reduce框架和云计算数据服 ...