https://oj.leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
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.
public int lengthOfLongestSubstringTwoDistinct(String s)
这一题其实和 http://blog.youkuaiyun.com/chaochen1407/article/details/42238259(Longest substring without repeating character)是同出一辙的。用快慢指针来表示当前窗口的头尾,用一个哈希表来维护窗口的内容。尾指针不断前行,然后将内容放进哈希表里维护。当哈希表的size > 2的时候头指针就不断收缩直到哈希表的size回归2为止。然后在这个过程里维护一个最大长度值即可。给出代码如下:
public int lengthOfLongestSubstringTwoDistinct(String s) {
HashMap<Character, Integer> cached = new HashMap<Character, Integer>();
int head = 0;
int res = 0;
for(int i = 0; i < s.length(); i++){
if(cached.containsKey(s.charAt(i))){
cached.put(s.charAt(i), cached.get(s.charAt(i)) + 1);
res = Math.max(res, i - head + 1);
}else{
int cur_res = i - head + 1;
cached.put(s.charAt(i), 1);
cur_res = cached.size() > 2 ? cur_res - 1 : cur_res;
res = Math.max(res, cur_res);
while(cached.size() > 2){
Character head_c = s.charAt(head);
cached.put(head_c, cached.get(head_c) - 1);
if(cached.get(head_c) == 0)
cached.remove(head_c);
head++;
}
}
}
return res;
}
本文介绍了一种使用快慢指针与哈希表相结合的方法来解决LeetCode上的一道题目:寻找字符串中最长的包含最多两个不同字符的子串。通过不断移动尾指针并更新哈希表,当哈希表大小超过2时则收缩头指针直至满足条件,最终找到符合条件的最长子串。
716

被折叠的 条评论
为什么被折叠?



