首页 > 代码库 > 159. Longest Substring with At Most Two Distinct Characters
159. Longest Substring with At Most Two Distinct Characters
public int lengthOfLongestSubstringTwoDistinct(String s) { //sliding window if(s == null || s.length() < 3) return s.length(); Set<Character> set = new HashSet<>(); int max = 0, index = 0; // use index to record left bar of window for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(!set.contains(c)) { if(set.size() >= 2) { for(int j = i - 1; j >= 0; j--) // scan from i - 1 to 0 if(s.charAt(j) != s.charAt(i - 1)) { set.remove(s.charAt(j)); index = j + 1; break; } } set.add(c); } max = Math.max(i - index + 1, max); } return max; }
159. Longest Substring with At Most Two Distinct Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。