leetcode 括号组合题目 20 是否是有效括号 32 最大有效括号 301 去掉无效括号

时间:2021-11-04 06:19:52

20. Valid Parentheses 有效括号

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

判断一个字符串是否是有效的括号组合

思路,依次将这些字符入栈,判断栈顶元素与当前元素是否是对应上的,是则pop,不是则入栈,到最后判断栈是否为空。

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     bool isValid(string s) {  
  4.         stack<char> result;  
  5.         int n=s.size();  
  6.         if(n==0) return true;  
  7.      for(int i=0;i<n;i++)  
  8.             {  
  9.                 if(result.empty())  
  10.                     result.push(s[i]);  
  11.                 else if(result.top()=='('&&s[i]==')'||  
  12.                       result.top()=='['&&s[i]==']'||  
  13.                       result.top()=='{'&&s[i]=='}')   
  14.                         result.pop();  
  15.                 else  
  16.                     result.push(s[i]);  
  17.                   
  18.             }  
  19.             return result.empty();  
  20.     }  
  21. };  

别人的思路:

这种方法能够更快的判断不符合条件的字符串,不需要将字符串遍历完成。

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     bool isValid(string s) {  
  4.         stack<char> paren;  
  5.         for (char& c : s) {  
  6.             switch (c) {  
  7.                 case '(':   
  8.                 case '{':   
  9.                 case '[': paren.push(c); break;  
  10.                 case ')'if (paren.empty() || paren.top()!='('return falseelse paren.pop(); break;  
  11.                 case '}'if (paren.empty() || paren.top()!='{'return falseelse paren.pop(); break;  
  12.                 case ']'if (paren.empty() || paren.top()!='['return falseelse paren.pop(); break;  
  13.                 default: ; // pass  
  14.             }  
  15.         }  
  16.         return paren.empty() ;  
  17.     }  
  18. };  

注意:只要当前的字符是)}]三个的一个,如果不能与栈顶结合,那就说明这个字符串是错误的。比如下面的代码。

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     bool isValid(string s) {  
  4.         stack<char> result;  
  5.         for(auto & a:s){  
  6.             if(a=='(') result.push(')');  
  7.             else if(a=='{') result.push('}');  
  8.             else if(a=='[')  result.push(']');  
  9.             else if(result.empty()||result.top()!=a)//这里直接出栈判断  
  10.                 return false;  
  11.             else result.pop();  
  12.         }  
  13.         return result.empty();  
  14.     }  

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
查看回溯部分

32. Longest Valid Parentheses 最长有效括号组合


动态规划:

  1. s and \text{s}[i - 1] = \text{‘(’}s[i1]=‘(’, i.e. string looks like ``.......()" \Rightarrow.......()"

    \text{dp}[i]=\text{dp}[i-2]+2dp[i]=dp[i2]+2

    We do so because the ending "()" portion is a valid substring anyhow and leads to an increment of 2 in the length of the just previous valid substring's length.

  2. \text{s}[i] = \text{‘)’}s[i]=‘)’ and \text{s}[i - 1] = \text{‘)’}s[i1]=‘)’, i.e. string looks like ``.......))" \Rightarrow.......))"

    if \text{s}[i - \text{dp}[i - 1] - 1] = \text{‘(’}s[idp[i1]1]=‘(’ then

    \text{dp}[i]=\text{dp}[i-1]+\text{dp}[i-\text{dp}[i-1]-2]+2dp[i]=dp[i1]+dp[idp[i1]2]+2

    class Solution {
    public:
        int longestValidParentheses(string s) {
            int n=s.size();
            if(n<=1) return 0;
            int res=0;
            vector<int> dp(n,0);
            if(s[0]=='('&&s[1]==')')
            {
                dp[1]=2;
                res=2;
            }
            for(int i=2;i<n;i++)//注意这里并不是奇偶数的遍历,因为不一定是奇数或者偶数为是有效的
            {
                if(s[i]==')')
                {
                    if(s[i-1]=='(')
                        dp[i]=dp[i-2]+2;
                    else if(s[i-1-dp[i-1]]=='(')
                        dp[i]=dp[i-1]+dp[i-1-dp[i-1]-1]+2;
                }
                res=max(res,dp[i]);
            }
            return res;
        }
    };

    方法3 栈

  3. 方法4  空间1 left right 

public class Solution {
    public int longestValidParentheses(String s) {
        int left = 0, right = 0, maxlength = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxlength = Math.max(maxlength, 2 * right);
            } else if (right >= left) {
                left = right = 0;
            }
        }
        left = right = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxlength = Math.max(maxlength, 2 * left);
            } else if (left >= right) {
                left = right = 0;
            }
        }
        return maxlength;
    }
}
301. Remove Invalid Parentheses

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Examples:

"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]