# Code language: Python classSolution: defminAddToMakeValid(self, s: str) -> int: cnt, ans = 0, 0 for c in s: if c == '(': cnt += 1 else: cnt -= 1 if cnt < 0: ans, cnt = ans + 1, 0 return ans + cnt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Code language: Java classSolution { publicintminAddToMakeValid(String s) { intcnt=0, ans = 0; for (inti=0, n = s.length(); i < n; ++i) { if (s.charAt(i) == '(') ++cnt; else { if (--cnt < 0) { ++ans; ++cnt; } } } return cnt + ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: C++ classSolution { public: intminAddToMakeValid(string s){ int cnt = 0, ans = 0; for (char c: s) { if (c == '(') ++cnt; else { if (--cnt < 0) { ++ans; ++cnt; } } } return cnt + ans; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Code language: JavaScript */ /** * @param {string} s * @return {number} */ var minAddToMakeValid = function(s) { let cnt = 0, ans = 0; for (let c of s) { if (c == '(') ++cnt; else { if (--cnt < 0) { ++ans; ++cnt; } } } return cnt + ans; };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Code language: Go */ funcminAddToMakeValid(s string)int { cnt, ans := 0, 0 for _, c := range s { if c == '(' { cnt++ } else { cnt-- if cnt < 0 { ans++; cnt = 0; } } } return cnt + ans }