NumberOfBalanced"()"InAnExpression


public class Main {
    
    //  Q: Check for balanced parentheses in an expression
    // input s: (()())
    // Output: 3
  
    public static void main(String[] args) {
        String s="(()())";
        System.out.println(checkbalance(s));
    }

  public static int checkbalance(String s){
      Stack stack = new Stack<>();
      int open=0;
      int close=0;
      for(Character c: s.toCharArray()){
          if(c=='('){
         stack.push(c);
              open++;
          }else if(c==')'){
              if(!stack.isEmpty()){
                  //拿下来
            stack.pop();
              close++;
              }
          }
      }
      if(open==close){
        return open;
      }else{
        return -1;
      }
      
      
  }
        
        
        
        
        
}

你可能感兴趣的:(NumberOfBalanced"()"InAnExpression)