zoukankan      html  css  js  c++  java
  • LeetCode 1249. Minimum Remove to Make Valid Parentheses

    原题链接在这里:https://leetcode.com/problems/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 <= 10^5
    • s[i] is one of  '(' , ')' and lowercase English letters.

    题解:

    From left to right, accoulate left open parenthese. 

    When encountering ")" and there is no more left "(", then this should be ignored.

    Do the same thing from right left.

    Time Complexity: O(n). n = s.length().

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public String minRemoveToMakeValid(String s) {
     3         if(s == null || s.length() == 0){
     4             return s;
     5         }
     6         
     7         StringBuilder sb = new StringBuilder();
     8         int left = 0;
     9         for(char c : s.toCharArray()){
    10             if(c == '('){
    11                 left++;
    12             }else if(c == ')'){
    13                 if(left == 0){
    14                     continue;
    15                 }
    16                 
    17                 left--;
    18             }
    19             
    20             sb.append(c);
    21         }
    22         
    23         StringBuilder res = new StringBuilder();
    24         for(int i = sb.length()-1; i>=0; i--){
    25             char c = sb.charAt(i);
    26             if(c == '(' && left-- > 0){
    27                 continue;
    28             }
    29             
    30             res.append(c);
    31         }
    32         
    33         return res.reverse().toString();
    34     }
    35 }

    类似Remove Invalid ParenthesesMinimum Add to Make Parentheses Valid.

  • 相关阅读:
    设计模式之代理模式
    Java面试总结系列之Collections.sort()
    Scala基础
    Win7 电脑设置临时网络,无法加入网络;internet禁止网络共享
    Java面试题系列 提高Java I/O 性能
    电子商务中:B2C、B2B、C2B、C2C、O2O、P2P
    JVM内存格局总结
    Dubbo相关博文整理
    Java面试题汇总(一)
    Java多线程总结
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11980982.html
Copyright © 2011-2022 走看看