ogv

Untitled

ogv
Nov 20th, 2019
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.58 KB | None | 0 0
  1. // Runtime: 0 ms, faster than 100.00% of Java online submissions for Minimum Add to Make Parentheses Valid.
  2. class Solution {
  3.     public int minAddToMakeValid(String S) {
  4.         int balance = 0;
  5.         int fix = 0;
  6.        
  7.         for (int i = 0; i < S.length(); i++)
  8.             if (S.charAt(i) == '('){
  9.                 if (balance > 0) balance++;
  10.                 else balance = 1;
  11.             } else {
  12.                 balance--;
  13.                 if (balance < 0) fix++;
  14.             }
  15.        
  16.         if (balance > 0) fix += balance;
  17.        
  18.         return fix;
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment