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

题解:

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 }

类似Max Consecutive Ones II.

相关文章:

  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-03
  • 2021-08-01
猜你喜欢
  • 2021-12-29
  • 2022-12-23
  • 2021-10-14
  • 2022-12-23
  • 2021-10-23
  • 2021-09-25
  • 2022-12-23
相关资源
相似解决方案