Time limite exceeded , but is this correct ?


  • 0
    W
    public int longestValidParentheses(String s){
    	
    	String temp = s;
    	int longest = 0;
    	int start=0,end=0;
    	int tempLong=0;
    	while(temp.length()>0&&end<s.length()){
    		int result = isValid(s,start,end);
    		if(result!=-1){
    			tempLong = result;
    			end++;
    			if(tempLong>longest){
    				longest = tempLong;
    			}
    		}else{
    			tempLong= 0;
    			start = end;
    			end=end+1;
    		}
    	}
    	return longest;
    }
    
    public int isValid(String s, int start, int end){
    	int tempLong = 0;
    	if(s.charAt(start)==')'){
    		return -1;
    	}
    	int left=0 ,right =0;
    	for(int i  = start;i<=end;i++){
    		if(s.charAt(i)=='('){
    			left++;
    		}else{
    			right++;
    		}
    		if(left==right){
    			tempLong=tempLong+left+right;
    			left=0;
    			right= 0;
    		}
    		if(right>left){
    			return -1;
    		}
    	}
    	if(end ==s.length()-1){
    		return tempLong+Math.min(left, right)*2;
    	}
    	return tempLong;
    }

Log in to reply
 

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