My java solution with Traversing the array twice


  • 0
    H
    class Solution {
        public int longestValidParentheses(String s) {
            int left = 0;
            int right = 0;
            int dist = 0;
            int max_dist = 0;
            for(int i = 0; i<s.length();i++){
                if(s.charAt(i)=='('){
                    left++;
                    dist++;
                }
                   
                if(s.charAt(i)==')'){
                    right++;
                    dist++;
                }
                if(right==left){
                    max_dist = max_dist>dist?max_dist:dist;
                }
                  
                if(right>left){
                    left=0;
                    right=0;
                    dist = 0;
                    
                }
                
            }
            left = 0;
            right = 0;
            dist = 0;
            for(int i = s.length()-1; i>=0;i--){
                if(s.charAt(i)=='('){
                    left++;
                    dist++;
                }
                   
                if(s.charAt(i)==')'){
                    right++;
                    dist++;
                }
                if(right==left){
                    max_dist = max_dist>dist?max_dist:dist;
                }
                  
                if(right<left){
                    left=0;
                    right=0;
                    dist = 0;
                    
                }
                
            }
          
            return max_dist;
        }
    }
    

Log in to reply
 

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