Simple Java Solution using LinkedHashSet


  • 0
    S

    I'm using LinkedHashSet to keep track of the number of unique elements currently in consideration. When a repeating element is found, I remove elements from the HashSet in order until there are no repetitions. I keep track of maxlength before removal and after insertion.

    public int lengthOfLongestSubstring(String str) {
        LinkedHashSet<Character> mapper = new LinkedHashSet<Character>();
        int maxlen = 0;
        for(int i=0; i<str.length(); i++){
            if(mapper.contains(str.charAt(i))){
                maxlen = Math.max(maxlen, mapper.size());
                while(mapper.contains(str.charAt(i))){
                    for(char k : mapper){
                        mapper.remove(k);
                        break;
                    }
                }
                mapper.add(str.charAt(i));
            }
            else{
                mapper.add(str.charAt(i));
                maxlen = Math.max(maxlen, mapper.size());
            }
        }   
        return maxlen;
    }
    

Log in to reply
 

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