您的位置:首页 > 其它

Leetcode 159 Longest Substring with At Most Two Distinct Characters

2017-06-15 14:33 351 查看
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.
使用双指针。
要求最多只有两个字母,那么在遇到新的字母的时候,就要移动low指针到新的起点
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if(s == null || s.length() <= 0){//corner cases
return 0;
}

int low = 0;
int high = 0;
int result = 0;
Map<Character, Integer> map = new HashMap<>();
int left = s.length();

for(int i = 0; i < s.length(); i++){
if(map.size() == 2 && !map.containsKey(s.charAt(i))){//出现新的char
left = s.length();
for(int index : map.values()){//找到char里面出现位置最左边的那个
left = Math.min(left, index);
}
map.remove(s.charAt(left));
low = left + 1;
}
map.put(s.charAt(i),i);//如果是不足俩char或者是重复的 就直接add或者update value 比如aaaaa value就是最右边的a的index

result = Math.max(result, i - low + 1);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: