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的更多相关文章

  1. [LeetCode#246] Missing Ranges Strobogrammatic Number

    Problem: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked a ...

  2. LeetCode 163. Missing Ranges (缺失的区间)$

    Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], ...

  3. [LeetCode#163] Missing Ranges

    Problem: Given a sorted integer array where the range of elements are [lower, upper] inclusive, retu ...

  4. [leetcode]163. Missing Ranges缺失范围

    Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, up ...

  5. [LeetCode] 163. Missing Ranges 缺失区间

    Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, up ...

  6. ✡ leetcode 163. Missing Ranges 找出缺失范围 --------- java

    Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], ...

  7. 【LeetCode】Missing Ranges

    Missing Ranges Given a sorted integer array where the range of elements are [lower, upper] inclusive ...

  8. [LeetCode] 228. Summary Ranges 总结区间

    Given a sorted integer array without duplicates, return the summary of its ranges. Example 1: Input: ...

  9. [LeetCode] Strobogrammatic Number III 对称数之三

    A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside ...

随机推荐

  1. BI任务列表

    了解点击流系统和pv/uv的相关计算 关于pv的那些事!! ···············································2014-09-10 homework做了些什 ...

  2. PHP&nbsp;支持的协议/封装协议列表

    附录 L. 支持的协议/封装协议列表 目录 文件系统 Socket HTTP 和 HTTPS FTP 和 FTPS PHP 输入/输出流 压缩流 Secure Shell 2 音频流  以下是 PHP ...

  3. 简洁JS 日历控件 支持日期和月份选择

    原文出处 以下这个JS日历控件是我的闲暇之余自己编写的,所有的代码全部在IE7/IE8/Firefox下面测试通过, 而且可以解决被iframe层遮盖的问题.现在只提供两种风格(简洁版和古典版)和两种 ...

  4. AsyncTask理解- Day36or37

    AsyncTask理解- Day36or37 mobile 5.0 1.手机归属地查询 AtoolsActivity Assets目录特点 该文件是原生文件,不会对里面的文件进行编码 该文件只支持读取 ...

  5. 网页快照 - C#实现

    /// <summary> /// 图片类型枚举 /// </summary> public enum ImageType { GIF = , JPG = , PNG = } ...

  6. Android中为APP创建快捷方式的原理(自己的理解)

    我们首先来看Android中为APP创建快捷方式的原理: 从图上可以看出,Android大致分7步完成快捷方式的创建: 第一步:Android系统的launcher程序会调用它的pickShortcu ...

  7. 开发错误日志之No matching bean of type [xxx] found for dependency

    No matching bean of type [org.springframework.data.mongodb.core.MongoTemplate] found for dependency ...

  8. RecordSet .CacheSize, Properties,CurserType,PageSize

    使用 CacheSize 属性可以控制一次要从提供者那里将多少个记录检索到本地内存中.例如,如果 CacheSize 为 10,首次打开 Recordset 对象后,提供者将把前 10 个记录检索到本 ...

  9. 【python】原始字符创

    原始字符串语法在字符串前加"r" 如 tem=r"h\c\d\n"print(tem) 结果:h\c\d\n 注意:字符串结尾不能是\,否则报错,应对措施将\单 ...

  10. eclipse/myeclipse选中编辑区域文件,Package Explorer定位文件所在项目及目录

    eclipse/myeclipse选中编辑区域文件,Package Explorer定位文件所在项目及目录 1. 打开Package Explorer(若没有,可以按照如下路径点击: Window菜单 ...