[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 ...
随机推荐
- sublime 2如何进入vim模式
点击菜单栏[Preferences]——[Settings - Defaults] 查找: "ignored_packages": ["Vintage"] 改为 ...
- sql if
SELECT a.id, a.EduSiteNo, a.EduSiteName, a.SchoolId, a.LinkMan, a.Tel, a.Mobile, a.Fax, a.Address, C ...
- CI框架篇之控制器篇--设置路由(1)
CodeIgniter 定义默认控制器 当你的网站不存在某个URI 或者 用户直接从根目录访问的时候,CodeIgniter 会加载默认控制器. 打开 application/config/route ...
- oracle学习笔记3:基本的SQL语句
oracle基本的SQL语句和SQLSERVER基本一样,在这里只简单列出与SQLSERVER不一样的地方 1.select * from orderinfo where address = 'abc ...
- xp和win 2003远程桌面强制进入命令
xp和win 2003远程桌面强制进入命令 注意:端口号也可以不写 如果是在win 2003里面进行踢人的话可以用命令: mstsc /console /v:172.25.100.27:3389 如果 ...
- C# 控制台窗口的显示与隐藏
1. 定义一个Consolse帮助类,如下: /// <summary> /// 控制台帮助类 /// </summary> public static class Conso ...
- ios专题 - 安全
iOS通过以下几种机制来保全整个系统的安全性: 一:系统结构 所有iOS设备中,系统与硬件都高度集成,从系统启动.系统更新.应用的安装.应用的运行时等多个方面来保全系统的安全,具体包括: 1:所有iO ...
- js实现文件上传,删除效果
效果图: 刚开始: 点击按钮"选择更多后",可以添加很多选择文件: 点击按钮"删除"后: 实现代码: <!DOCTYPE html><html ...
- CSS中:nth-child和JQuery:eq的区别
$("li:nth-child(n)")选择器与$("li:eq(n)")选择器的不同之处在于:$("li:eq(n)")选择器只匹配一个元 ...
- web系统
现在的web系统已经越来越多的应用缓存技术,而且缓存技术确实是能实足的增强系统性能的.我在项目中也开始接触一些缓存的需求. 开始简单的就用jvm(java托管内存)来做缓存,这样对于单个应用服务器来说 ...