easy java code with HashMap.


  • 1
    L
        public static int lengthOfLongestSubstring(String s) {
    	int maxLen = 0;
    	if(s.length() == 0 || s == null){
    		return 0;
    	}
    	Map<Character, Integer> hashMap = new HashMap<>();
    	for(int i = 0,j = 0;j < s.length();){
    		if(hashMap.containsKey(s.charAt(j)) == false){
    			hashMap.put(s.charAt(j), j);
    			if(j - i + 1 > maxLen){
    				maxLen = j - i + 1;
    			}
    			j++;
    		}else {
    			hashMap.remove(s.charAt(i));
    			i++;
    		}
    	}
        return maxLen;
    }

Log in to reply
 

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