Sharing my unique code


  • 0
    S
    int longestValidParentheses(string s){
    int l(0),r(0);//l,r keep the numbers of right bracket numbers and left bracket numbers separately
    int temp(0),result(0);//temp keep the temporary biggest length 
    int index(-1);
    for(int i = 0;i<s.length();i++){// processing from right
    	if (s[i] == '\(') l++;
    	else if(s[i] == '\)') {
    		r++;
    		if (r == l) {//right bracket numbers equals left bracket numbers		
    			temp = 2*r;		
    			result = temp > result ? temp :result; }
    		if (r > l)  {r = l = 0; index = i;}// reset r and l to zeros
    	}
    }
    r = l = 0;
    for (int i = s.length();i>index;i--){//processing for left for last substring that r<l		
    	if (s[i] == '\)') r++;
    	else if(s[i] == '\(') {
    		l++;
    		if (r == l) { 			
    			temp = 2*l;		
    			result = temp > result ? temp :result; }
    		if (r < l)  r = l = 0;
    	}
    }
       return result;
     }

Log in to reply
 

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