1249. Minimum Remove to Make Valid Parentheses (M)

Minimum Remove to Make Valid Parentheses (M)

题目

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 <= 10^5
  • s[i] is one of '(' , ')' and lowercase English letters.

题意

将给定字符串中非法的括号删去。

思路

只要保证左右括号数量相等即可。先从左到右遍历,将所有无法匹配的')'删去,这样得到的字符串保证了'('的数量一定大于等于')'的数量;再从右到左遍历新字符串,将所有无法匹配的'('删去,最终得到的字符串一定满足'('和')'数量相等。


代码实现

Java

class Solution {
    public String minRemoveToMakeValid(String s) {
        StringBuilder sb = new StringBuilder();
        int cnt = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != ')') {
                sb.append(c);
                if (c == '(') cnt++;
            } else if (cnt > 0) {
                cnt--;
                sb.append(c);
            }
        }

        if (cnt == 0) return sb.toString();

        s = sb.toString();
        sb = new StringBuilder();
        cnt = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c != '(') {
                sb.insert(0, c);
                if (c == ')') cnt++;
            } else if (cnt > 0) {
                cnt--;
                sb.insert(0, c);
            }
        }

        return sb.toString();
    }
}
posted @ 2021-02-19 17:35  墨云黑  阅读(41)  评论(0编辑  收藏  举报