LeetCode 159. Longest Substring with At Most Two Distinct Characters

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

题解:

Longest Substring Without Repeating Characters类似。快慢指针维护substring的方法在Minimum Window Substring里有总结.

runner 扫过 char的frequency加一. 条件count++.

当count > 2后移动walker直到count减到2

Time Complexity: O(n), 窗口只移动一遍. Space: O(1). map size.

AC Java:

 1 public class Solution {
 2     public int lengthOfLongestSubstringTwoDistinct(String s) {
 3         int res = 0;
 4         int [] map = new int[256];
 5         int walker = 0;
 6         int runner = 0;
 7         int count = 0;
 8         while(runner < s.length()){
 9             if(map[s.charAt(runner++)]++ == 0){
10                 count++;
11             }
12             while(count > 2){
13                 if(map[s.charAt(walker++)]-- == 1){
14                     count--;
15                 }
16             }
17             res = Math.max(res, runner - walker);
18         }
19         return res;
20     }
21 }

类似Longest Substring with At Most K Distinct CharactersFruit Into BasketsMax Consecutive Ones II.

posted @ 2016-02-05 01:38  Dylan_Java_NYC  阅读(619)  评论(0编辑  收藏  举报