题目

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:

  1. Input: s = "lee(t(c)o)de)"
  2. Output: "lee(t(c)o)de"
  3. Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

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

Example 3:

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

Example 4:

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

Constraints:

  • 1 <= s.length <= 10^5
  • s[i] is one of '(' , ')' and lowercase English letters.

题意

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

思路

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


代码实现

Java

  1. class Solution {
  2. public String minRemoveToMakeValid(String s) {
  3. StringBuilder sb = new StringBuilder();
  4. int cnt = 0;
  5. for (int i = 0; i < s.length(); i++) {
  6. char c = s.charAt(i);
  7. if (c != ')') {
  8. sb.append(c);
  9. if (c == '(') cnt++;
  10. } else if (cnt > 0) {
  11. cnt--;
  12. sb.append(c);
  13. }
  14. }
  15. if (cnt == 0) return sb.toString();
  16. s = sb.toString();
  17. sb = new StringBuilder();
  18. cnt = 0;
  19. for (int i = s.length() - 1; i >= 0; i--) {
  20. char c = s.charAt(i);
  21. if (c != '(') {
  22. sb.insert(0, c);
  23. if (c == ')') cnt++;
  24. } else if (cnt > 0) {
  25. cnt--;
  26. sb.insert(0, c);
  27. }
  28. }
  29. return sb.toString();
  30. }
  31. }