0921.cpp (374B)
1 class Solution { 2 public: 3 int minAddToMakeValid(const string &s) { 4 int res = 0, cnt = 0; 5 for (char c : s) { 6 if (c == '(') 7 cnt++; 8 else if (c == ')') { 9 if (cnt > 0) 10 cnt--; 11 else 12 res++; 13 } 14 } 15 return res + cnt; 16 } 17 };