LeetCode Longest Substring with At Most Two Distinct Characters

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Longest Substring with At Most Two Distinct Characters相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

Longest Substring Without Repeating Characters类似。

维护一个窗口[walker, runner]. 同时维护一个HashMap<Character,Integer>, key是字符, value是字符出现次数。要保证hm.size()<=2.

在runner<s.length()的条件下,若是hm已经包含s.charAt(runner), 对应数量加一即可。

若是不包含s.charAt(runner), 此时要看hm.size()是否小于2, 若是小于2, 插入新的数据即可。若是已经等于2了,说明不能插入了,此时就要开始移动walker.

从hm中减掉walker对应的char的数量,知道hm.size()不再等于2即可。

Time Complexity: O(n), 窗口只移动一遍. Space: O(1). HashMap的大小控制在2.

AC Java:

 1 public class Solution {
 2     public int lengthOfLongestSubstringTwoDistinct(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
 9         
10         int walker = 0;
11         int runner = 0;
12         while(runner < s.length()){
13             if(hm.containsKey(s.charAt(runner))){
14                 hm.put(s.charAt(runner), hm.get(s.charAt(runner))+1);
15                 runner++;
16             }else if(hm.size() < 2){
17                 hm.put(s.charAt(runner), 1);
18                 runner++;
19             }else{
20                 while(hm.size() == 2){
21                     hm.put(s.charAt(walker),hm.get(s.charAt(walker))-1);
22                     if(hm.get(s.charAt(walker)) == 0){
23                         hm.remove(s.charAt(walker));
24                     }
25                     walker++;
26                 }
27             }
28             res = Math.max(res,runner-walker);
29         }
30         return res;
31     }
32 }

 

以上是关于LeetCode Longest Substring with At Most Two Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix