括号问题

**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.

class Solution {
public:
    bool isValid(string s) {
        if(s.size()<=1)
          return false;
        stack temp;
        
        for(int i=0;i

**32. Longest Valid Parentheses **
跟上题思路相同
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
代码如下:

class Solution {
public:
    int longestValidParentheses(string s) {
        if(s.size()<=1)
          return 0;
        stack temp;
        int last = -1;
        int maxLen = 0;
        for(int i=0;i

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

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

代码如下:

class Solution {
public:
    vector generateParenthesis(int n) {
        vector rec;
        dfs(n,n,"",rec);
        return rec;
    }
    void dfs(int left,int right,string out,vector &rec)
    {
        if(left>right)
          return;
        if(left==0&&right==0)
          rec.push_back(out);
        if(left>0)
          dfs(left-1,right,out + "(",rec);
        if(right>0)
          dfs(left,right-1,out + ")",rec);
    }
};

你可能感兴趣的:(括号问题)