My O(n) Java solution,very easy


  • 0
    U
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() == 0){
        	return 0;
        }
        int max = 0;
        LinkedList<Character> set = new LinkedList<>();
        char c = ' ';
        for(int i = 0 ; i < s.length(); i++){
        	c = s.charAt(i);
        	if(set.contains(c)){
        		if(set.size() > max){
        			max = set.size();
        		}
        		while(true){
        			char index = set.getFirst();
        			if(index != c){
        				set.removeFirst();
        			}else{
        				break;
        			}
        		}
        		set.removeFirst();
        	}
        	set.addLast(c);
        }
        
        if(set.size() > max){
        	max = set.size();
        }
        
        return max;
    }

Log in to reply
 

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