Advertisement
1988coder

921. Minimum Add to Make Parentheses Valid

Dec 9th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.51 KB | None | 0 0
  1. /*
  2. Time Complexity: O(N)
  3. Space Complexity: O(1)
  4. N = length of the string
  5. */
  6. class Solution {
  7.     public int minAddToMakeValid(String S) {
  8.         if (S == null || S.length() == 0) {
  9.             return 0;
  10.         }
  11.        
  12.         int result = 0;
  13.         int count = 0;
  14.         for (char s : S.toCharArray()) {
  15.             count += s == '(' ? 1 : -1;
  16.             if (count < 0) {
  17.                 result++;
  18.                 count = 0;
  19.             }
  20.         }
  21.        
  22.         return result + count;
  23.     }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement