程序媛詹妮弗
终身学习

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.

 

题意:

给定字符串,找出至多包含两种字符的最长子串。

 

思路:

  j          
 “e c e b a”
   i                    e-0
     i                  c-1
         i              e-2
-------map.size()<= 2
            i           b-3  此时移动 j 

 

代码:

 1 class Solution {
 2     public int lengthOfLongestSubstringTwoDistinct(String s) {
 3         if(s.length() < 2) return s.length();
 4         HashMap<Character, Integer> map = new HashMap<>();
 5         int result = 0;
 6         int j = 0;
 7         for(int i = 0; i < s.length(); ){
 8             char c = s.charAt(i);
 9             if(map.size() <= 2){
10                 map.put(c, i);
11                 i++;
12             }
13             if(map.size() > 2){
14                 int leftMost = s.length();
15                 for(int n : map.values()){
16                     leftMost = Math.min(leftMost, n);
17                 }
18                 map.remove(s.charAt(leftMost));
19                 j = leftMost + 1;   
20             }
21             result = Math.max(result, i - j );
22         }
23           return result;  
24     }
25 }

 

posted on 2018-06-20 03:37  程序媛詹妮弗  阅读(119)  评论(0编辑  收藏  举报