码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Longest Substring with At Most Two Distinct Characters

时间:2016-02-05 11:29:14      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里: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

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5182617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!