[LeetCode#159] Missing Ranges Strobogrammatic Number
Problem:
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.
Analysis:
This is a very very typical question in using slide window. Why?
The problem asks the substring to meet certain characteristic. The substring means the target must be a series of succsive characters. Basic idea:
The problem restricts the target must contain no more than 2 distinct characters.
Apparently we should use a HashMap to record such information. (when there is a quantitive restriction, you should firstly think about using HashMap rather than HashSet) Weaving Picature:
Maintain two boundary for a window : "front" and "end", recording the relevent information(according problems' requirement and restriction) through a HashMap. For this problem, we maintain "HashMap<Character, Integer>" to record Character's count in the window. It means we at most allow two distinct Characters in the HashMap. When the end pointer was moved onto a new character.
case1. iff the charcter existed in the HashMap, we can directly include it into our current window.
case2. iff the charcter is not existed in the HashMap, we may have to adjust the start pointer of slide window to make it is valid to add the new charcter into the window.
Note: you should not hesitate over wheather to use hashmap's size() or "hashmap.contains(c)" as the first level "if-else" checking. Since we may not need to care the hashmap's size when case1.
---------------------------------------------------------------------
if (!map.containsKey(c)) {
...
}else {
...
} For case 2.
a. Iff the map's size is less than 2, we can directly include it into window.
if (map.size() < 2) {
map.put(c, 1);
end = i;
} b. Iff the map's size is equal to 2, we need to adjust the window's start boundary.
Skill: keep on moving start boundary, until one character was totally wiped out from the window.
while (map.size() == 2) {
char discard = s.charAt(start);
start++;
map.put(discard, map.get(discard) - 1);
if (map.get(discard) == 0)
map.remove(discard);
}
map.put(c, 1);
end = i;
Note: we don't need to care wheather "start" would exceed the s.length, since when there is only one character in the window, it would exit the while loop. This is beautiful part in using while-loop in slide window.
Solution 1:
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null)
throw new IllegalArgumentException("s is null");
int len = s.length();
if (len <= 2)
return len;
int start = 0, end = 0, max = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer> ();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (!map.containsKey(c)) {
if (map.size() < 2) {
map.put(c, 1);
end = i;
} else{
while (map.size() == 2) {
char discard = s.charAt(start);
start++;
map.put(discard, map.get(discard) - 1);
if (map.get(discard) == 0)
map.remove(discard);
}
map.put(c, 1);
end = i;
}
} else{
map.put(c, map.get(c) + 1);
end = i;
}
max = Math.max(max, end - start + 1);
}
return max;
}
}
Improvement Analysis:
Even my first solution is right, there are many room for improving it regarding the elegance of code.
1. When we use slide window, "i" is actually the end boundary of slide window. We don't need to maintain a end variable. And we always measure the window, after it was adjusted into valid. (i is not change!)
max = Math.max(max, i - start + 1); 2. The purpose of adjusting window is to make the current end boundary valid. And after the adjust (or no need for the adjust), we finally need to put the character at "end" into the map.
while (map.size() == 2) {
char discard = s.charAt(start);
start++;
map.put(discard, map.get(discard) - 1);
if (map.get(discard) == 0)
map.remove(discard);
}
map.put(c, 1);
Solution 2:
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null)
throw new IllegalArgumentException("s is null");
int len = s.length();
if (len <= 2)
return len;
int start = 0, end = 0, max = 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer> ();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (!map.containsKey(c)) {
while (map.size() == 2) {
char discard = s.charAt(start);
start++;
map.put(discard, map.get(discard) - 1);
if (map.get(discard) == 0)
map.remove(discard);
}
map.put(c, 1);
} else{
map.put(c, map.get(c) + 1);
}
max = Math.max(max, i - start + 1);
}
return max;
}
}
[LeetCode#159] Missing Ranges Strobogrammatic Number的更多相关文章
- [LeetCode#246] Missing Ranges Strobogrammatic Number
Problem: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked a ...
- LeetCode 163. Missing Ranges (缺失的区间)$
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], ...
- [LeetCode#163] Missing Ranges
Problem: Given a sorted integer array where the range of elements are [lower, upper] inclusive, retu ...
- [leetcode]163. Missing Ranges缺失范围
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, up ...
- [LeetCode] 163. Missing Ranges 缺失区间
Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, up ...
- ✡ leetcode 163. Missing Ranges 找出缺失范围 --------- java
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], ...
- 【LeetCode】Missing Ranges
Missing Ranges Given a sorted integer array where the range of elements are [lower, upper] inclusive ...
- [LeetCode] 228. Summary Ranges 总结区间
Given a sorted integer array without duplicates, return the summary of its ranges. Example 1: Input: ...
- [LeetCode] Strobogrammatic Number III 对称数之三
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...
随机推荐
- angularjs-yeoman环境配置
yum install npm -y npm install -g grunt-cli bower yo generator-karma-require generator-angular-requi ...
- Controller里写自己需要的Action,参数的名字必须和路由设置的参数名一致
Controller里写自己需要的Action,参数的名字必须和路由设置的参数名一致,如果参数不一致,传过去为null
- wps批量使标题靠文档左边
- Windows I/O模型、同步/异步、阻塞/非阻塞
转载自:http://www.cppblog.com/tx7do/articles/5954.html 同步 所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回.按照这个定义,其实 ...
- AutoResetEvent 详解
AutoResetEvent 允许线程通过发信号互相通信.通常,此通信涉及线程需要独占访问的资源. 线程通过调用 AutoResetEvent 上的 WaitOne 来等待信号.如果 AutoRese ...
- 继续(3n+1)猜想
卡拉兹(Callatz)猜想已经在1001中给出了描述.在这个题目里,情况稍微有些复杂. 当我们验证卡拉兹猜想的时候,为了避免重复计算,可以记录下递推过程中遇到的每一个数.例如对n=3进行验证的时候, ...
- (三)Struts2 拦截器
所有的学习我们必须先搭建好Struts2的环境(1.导入对应的jar包,2.web.xml,3.struts.xml) 第一节:拦截器简介 (百度百科Struts2) Struts2 拦截器是在访问某 ...
- 最新的 iOS 申请证书与发布流程(2016.12)
今天刚好客户定制的APP需要上架,也提供了新的开发者账号,所以就顺带把申请证书与发布流程写一遍. 证书是什么? 上面这个就是我们申请好证书后,下载到本地的.cer文件,也就是常说的开发证书与发布证书的 ...
- Python:模块引用
#!/usr/bin/python3 #Filename function.py #导入模块 import sys #导入function.py#function.py 文件import functi ...
- 关于php的一些开源程序
最好用的当属thinksns,目前更新到4.3.4, 社交型网站. 此网站提供大量源码,有时间可以去看看:http://down.admin5.com/