[LeetCode] 1249. Minimum Remove to Make Valid Parentheses 移除無效的括號



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 1:

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.

Example 2:

Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Example 4:

Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either'(' , ')', or lowercase English letter.

這道題給了一個有括號的字符串,說是盡可能的少移除括號的個數,使得整個字符串變得合法,讓返回這個合法的字符串。LeetCode 有很多關於括號的題目,大部分的解題思路都很像,都是從左右括號的個數和位置入手,若只是想知道字符串是否合法,只需要統計左右括號的個數,任何時候右括號的個數都不能超過左括號的個數。而這道題要移除非法的括號,所以位置信息也很重要。這里使用一個棧 stack 來記錄左括號的位置,遍歷給定字符串s,若遇到了左括號,則將當前位置壓入棧,若遇到右括號,則判斷,若當前棧為空,說明前面沒有左括號了,則當前右括號就是非法的,標記當前位置為星號,若棧不為空,則移除棧頂元素,即移除一個左括號。這樣操作完成了之后,所有的非法右括號的位置都被標記了,而此時殘留在棧中的左括號也都是非法的,將其對應位置標記為星號。最后只要移除所有的星號,得到的就是合法的字符串了,參見代碼如下:


解法一:

class Solution {
public:
    string minRemoveToMakeValid(string s) {
        string res;
        stack<int> st;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(') st.push(i);
            else if (s[i] == ')') {
                if (st.empty()) s[i] = '*';
                else st.pop();
            }
        }
        while (!st.empty()) {
            s[st.top()] = '*'; st.pop();
        }
        for (char c : s) {
            if (c != '*') res += c;
        }
        return res;
    }
};

我們也可以優化一下空間復雜度,不用棧了,而是用兩個變量 left 和 right,分別表示左右括號的個數,先遍歷一遍給定字符串s,統計出所有的右括號的個數。然后再次遍歷給定字符串s,若遇左擴號了,判斷若此時 left 和 right 相等了,說明后面沒有多余的右括號了,此時的左括號就是非法的,則直接跳過,否則就讓 left 自增1。若遇到右括號了,則 right 先自減1,因為 right 表示的是后面還有的右括號的個數,若此時 left 等於0了,說明前面沒有對應的左括號了,則直接跳過,否則 left 自減1。對於所有沒有 continue 的情況,則均加入到結果 res 中,表示對應的字母,或者左右括號就是合法的,參見代碼如下:


解法二:

class Solution {
public:
    string minRemoveToMakeValid(string s) {
        string res;
        int left = 0, right = 0;
        for (char c : s) {
            if (c == ')') ++right;
        }
        for (char c : s) {
            if (c == '(') {
                if (left == right) continue;
                ++left;
            } else if (c == ')') {
                --right;
                if (left == 0) continue;
                --left;
            }
            res += c;
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1249


類似題目:

Minimum Number of Swaps to Make the String Balanced


參考資料:

https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/

https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/419402/JavaC%2B%2B-Stack

https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/419466/Constant-Space-Solution


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM