JAVA solution with O(1) space and O(n) time, using pointers


  • 0
    Z
    public class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
    	if(s == null || s.length() == 0){
    	    return 0;
    	}
    	int ans = 1;
    	int taga = 0, tagb = 0, change = 0;
    	for(int i = 1; i < s.length(); i++){
    	    if(s.charAt(i) != s.charAt(taga) && s.charAt(i) != s.charAt(tagb)){
    		taga = change;
    	        tagb = i;
    	    }
    	    if(s.charAt(i) != s.charAt(i-1)){
    	        change = i;
    	    }
    	    ans = Math.max(ans,i - taga+1);
    	}
    	return ans;
        }
    }
    

Log in to reply
 

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