「这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战」
移除无效的括号
LeetCode传送门1249. 移除无效的括号
题目
给你一个由 '('、')' 和小写字母组成的字符串 s。
你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。
请返回任意一个合法字符串。
有效「括号字符串」应当符合以下 任意一条 要求:
- 空字符串或只包含小写字母的字符串
- 可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
- 可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
- It is the empty string, contains only lowercase characters, or
- It can be written as AB (A concatenated with B), where A and B are valid strings, or
- It can be written as (A), where A is a valid string.
Example:
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
Input: s = "a)b(c)d"
Output: "ab(c)d"
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Constraints:
- s[i] is either'(' , ')', or lowercase English letter.
思考线
解题思路
题目中要我们返回合法的字符串
我们根据题意可以知道,任何不能成对匹配的()都应该被删除。我们可以用栈来记录成对的()。在遍历字符串的过程中我们记录所有出现的(的位置,如果出现)就去除掉末尾的(.
在记录的过程中值得注意的是
- 如果最后栈里面还有元素我们,对应的元素也是要删除的。
- 如果栈中没有元素,而我们遍历到了
),则该字符串也应该被删除。
当我们找到所有需要删除元素对应的index时,我们只要避免复制这些字符,我们就可以复制出合法的字符串了。
根据以上思路我们可以实现代码如下
function minRemoveToMakeValid(s: string): string {
const stack = [];
const del = []
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
stack.push(i)
} else if (s[i] === ')') {
if (stack.pop() ===undefined) {
del.push(i);
}
}
}
del.push(...stack);
let res = ''
for(let i = 0; i < s.length; i ++) {
if(del.includes(i)) {
del.shift()
continue;
}
res +=s[i]
}
return res;
};
时间复杂度
O(N): N. 其中N为字符串的长度。
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。