[LeetCode]159. Longest Substring with At Most Two Distinct Characters
来源:互联网 发布:正交矩阵和实对称矩阵 编辑:程序博客网 时间:2024/04/27 16:19
原题链接:https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
这也是一道带锁题,已经解锁的朋友可以选择做一做。这道题其实就是经典的窗口移动题,感觉难度其实是Medium。题目的要求是对于输入的字符串,要求返回只包含两个字母的子串最长的长度。
解法就是我们维护一个窗口的2个指针,一个指向窗口左端,一个指向窗口右端。然后右边的指针不断向右移动,如果窗口里的子串包含的字符种类数大于2种,则向右移动窗口的左指针,直到窗口重新恢复到包含字符种类数为2为止。时间复杂度是O(n)
代码如下:
public int lengthOfLongestSubstringTwoDistinct(String s) { if(s.length() == 0) return 0; int count = 0; HashMap<Character,Integer> map = new HashMap<>(); int start = 0; int len = 0; for(int i = 0;i<s.length();i++) { char c = s.charAt(i); if(map.containsKey(c)) { map.put(c,map.get(c)+1); } else { map.put(c,1); } if(map.get(c)==1) count++; while(count>2) { char c2 = s.charAt(start); map.put(c2,map.get(c2)-1); if(map.get(c2)<=0) { count--; } start++; } len = Math.max(i-start,len); } return len+1; }类似的窗口移动题目还有很多,如Longest Substring Without Repeating Characters 这道题,Code Ganker 已经给出了非常好的解决方案了。有关窗口移动题目思路都是一个模式,朋友们自己去总结哈。
0 0
- Leetcode-159.Longest Substring with At Most Two Distinct Characters
- Leetcode-159.Longest Substring with At Most Two Distinct Characters
- [LeetCode]159. Longest Substring with At Most Two Distinct Characters
- LeetCode 159. Longest Substring with At Most Two Distinct Characters
- Leetcode 159. Longest Substring with At Most Two Distinct Characters
- [Leetcode] Longest Substring with At Most Two Distinct Characters
- Leetcode Longest Substring with At Most Two Distinct Characters
- leetcode 159: Longest Substring with At Most Two Distinct Characters
- [Leetcode]Longest Substring with At Most Two Distinct Characters
- LeetCode - Longest Substring with At Most Two Distinct Characters
- Leetcode: Longest Substring with At Most Two Distinct Characters
- Leetcode 159 Longest Substring with At Most Two Distinct Characters
- Leetcode 159 Longest Substring with At Most Two Distinct Characters
- 159. Longest Substring with At Most Two Distinct Characters
- 159. Longest Substring with At Most Two Distinct Characters
- [leetcode] 159. Longest Substring with At Most Two Distinct Characters 解题报告
- LeetCode 159. Longest Substring with At Most Two Distinct Characters(最长字串)
- Leetcode 159. Longest Substring with At Most Two Distinct Characters (Hard) (cpp)
- JAVA中的Object类
- Minecraft题解
- 个人笔记 html 06 获取验证码之后倒计时功能
- 内联函数详解(未完成)
- 浏览器cannot read property 'msie' of undefined的解决方法
- [LeetCode]159. Longest Substring with At Most Two Distinct Characters
- 图解正向代理、反向代理、透明代理
- 蓝桥杯 历届试题 蚂蚁感冒 (模拟)
- [LeetCode]160. Intersection of Two Linked Lists
- HDU 1004 Let the Balloon Rise(map)
- 短作业优先与时间片轮转法
- 一次失败的j2v8集成
- Tuple and Tie
- cmd运行Java程序的问题