Category | Difficulty | Likes | Dislikes |
---|---|---|---|
algorithms | Medium (73.02%) | 234 | - |
只有满足下面几点之一,括号字符串才是有效的:
AB
(A
与 B
连接), 其中 A
和 B
都是有效字符串,或者(A)
,其中 A
是有效字符串。给定一个括号字符串 s
,在每一次操作中,你都可以在字符串的任何位置插入一个括号
s = "()))"
,你可以插入一个开始括号为 "(()))"
或结束括号为 "())))"
。返回 为使结果字符串 s
有效而必须添加的最少括号数。
示例 1:
输入:s = "())"
输出:1
示例 2:
输入:s = "((("
输出:3
提示:
1 <= s.length <= 1000
s
只包含 '('
和 ')'
字符。class Solution {public int minAddToMakeValid(String s) {// if (s == "" || s == null) {// return 0;// }// int zNum = 0;// int yNum = 0;// int ans = 0;// for (char c : s.toCharArray()) {// if (c == '(') {// zNum++;// } else if (c == ')') {// yNum++;// }// ans = yNum - zNum;// }// return Math.abs(ans);// }// res 记录插入次数int res = 0;// need 变量记录右括号的需求量int need = 0;for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '(') {// 对右括号的需求+1need++;}if (s.charAt(i) == ')') {// 对右括号的需求-1need--;if (need == -1) {need = 0;// 需插入一个左括号res++;}}}return res + need;}
}