[leetcode]159. Longest Substring with At Most Two Distinct Characters至多包含两种字符的最长子串

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

代码:

 class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if(s.length() < 2) return s.length();
HashMap<Character, Integer> map = new HashMap<>();
int result = 0;
int j = 0;
for(int i = 0; i < s.length(); ){
char c = s.charAt(i);
if(map.size() <= 2){
map.put(c, i);
i++;
}
if(map.size() > 2){
int leftMost = s.length();
for(int n : map.values()){
leftMost = Math.min(leftMost, n);
}
map.remove(s.charAt(leftMost));
j = leftMost + 1;
}
result = Math.max(result, i - j );
}
return result;
}
}
上一篇:java:struts框架2(方法的动态和静态调用,获取Servlet API三种方式(推荐IOC(控制反转)),拦截器,静态代理和动态代理(Spring AOP))


下一篇:从动态代理到Spring AOP(上)