Simple Java Solution in O(n) using HashMap


  • 0
    N
      public int lengthOfLongestSubstring(String s) {
    	if (s == null || s.length() == 0)
    		return 0;
    	
    	int subStringCount = 0, duplicatePosition = -1;
    	Map<Character, Integer> charMap = new HashMap<>();
    	int i=0;
    	while(i<s.length()) {
    		if (!charMap.containsKey(s.charAt(i))) {
    			charMap.put(s.charAt(i),i);
    			subStringCount = Math.max(subStringCount, i-duplicatePosition);
    			i++;
    		}
    			
    		else {
    			duplicatePosition=Math.max(charMap.put(s.charAt(i),i),duplicatePosition);
    			subStringCount = Math.max(subStringCount, i-duplicatePosition);
    			i++;
    		}
    
    	}
    	return subStringCount;
    }

Log in to reply
 

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