Easy to understand solution


  • 1
    A

    public class Solution {
    public int lengthOfLongestSubstring(String s) {

        if(s.length()==0) return 0;
        
        int i=0,j=0;
        int max_len = -1;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        
        while(j<s.length()) {
            if(map.containsKey(s.charAt(j))) {
                if(max_len < (j-i))
                    max_len = j-i;
                
                map.remove(s.charAt(i));
                ++i;
            } else {
                map.put(s.charAt(j), j);
                j++;
                if(max_len < (j-i))
                    max_len = j-i;
            }
        }
        return max_len;
    }
    

    }


Log in to reply
 

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