TLE showed in my code


  • 0
    H
    import java.util.Stack;
    public int lengthOfLongestSubstring(String s) {
            Stack<String> s1 = new Stack<String>();
    		Stack<String> s2 = new Stack<String>();
    		int length = 0;
    		int result = 0;
    		for(int i = 0; i < s.length(); i++){
    			String str = s.charAt(i) + "";
    			if(s1.isEmpty() || s1.search(str) == -1){
    				s1.push(str);
    				length++;
    			} else {
    				s2.push(str);
    				while(!s1.peek().equals(str)){
    					s2.push(s1.pop());
    					length--;
    				}
    				// clear
    				while(!s1.isEmpty()){
    					s1.pop();
    					length--;
    				}
    				while(!s2.peek().equals(str)){
    					s1.push(s2.pop());
    					length++;
    				}
    				s1.push(str);
    				length++;
    			}
    			// relax
    			if(result < length)
    				result = length;
    		}
            return result;
        }
    

    Is this code is correct?


Log in to reply
 

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