classSolution: defminAddToMakeValid(self, s: str) -> int: ans = cnt = 0 for c in s: if c == '(': cnt += 1 elif cnt > 0: cnt -= 1 else: ans += 1 return ans + cnt
classSolution { public: intminAddToMakeValid(string s){ int ans = 0; int leftCount = 0; for (auto &c : s) { if (c == '(') { leftCount++; } else { if (leftCount > 0) { leftCount--; } else { ans++; } } } ans += leftCount; return ans; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intminAddToMakeValid(char * s){ int ans = 0; int leftCount = 0; int length = strlen(s); for (int i = 0; i < length; i++) { char c = s[i]; if (c == '(') { leftCount++; } else { if (leftCount > 0) { leftCount--; } else { ans++; } } } ans += leftCount; return ans; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var minAddToMakeValid = function(s) { let ans = 0; let leftCount = 0; let length = s.length; for (let i = 0; i < length; i++) { const c = s[i]; if (c === '(') { leftCount++; } else { if (leftCount > 0) { leftCount--; } else { ans++; } } } ans += leftCount; return ans; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcminAddToMakeValid(s string) (ans int) { cnt := 0 for _, c := range s { if c == '(' { cnt++ } elseif cnt > 0 { cnt-- } else { ans++ } } return ans + cnt }