Java solution using Sliding Window concept


  • 0
    C
        // idea is to implement minimum window span logic
        public int lengthOfLongestSubstringTwoDistinct(String s) {
    		Map<Character, Integer> charMap = new HashMap<Character, Integer>();
    
    		int beg = 0, end = s.length() - 1, cur = 0, maxLength = 0;
    		boolean isValid = true;
    		while (cur <= end) {
    		    // increasing the window size 
    			while (cur <= end && charMap.size() <= 2) {
    				char ch = s.charAt(cur++);
    				charMap.computeIfPresent(ch, (k, v) -> v + 1);
    				charMap.computeIfAbsent(ch, v -> 1);
    			}
    			
    			// window size is invalid so need to remove the last character
    			if(charMap.size() > 2){
    			    maxLength = Math.max(maxLength, cur - beg - 1);
    			}
    			// window size is valid
    			else{
    			    maxLength = Math.max(maxLength, cur - beg);
    			}
    
                // shrinking the window size to make the substring valid
    			while (charMap.size() > 2) {
    				char ch = s.charAt(beg++);
    
    				charMap.put(ch, charMap.get(ch) - 1);
    				if (charMap.get(ch) == 0) {
    					charMap.remove(ch);
    				}
    			}
    		}
    
            return maxLength;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.