您的位置:首页 > 其它

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

2017-08-04 18:26 417 查看


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

class Solution {  

public:  

    bool isValid(string s) {  

        stack<char> result;  

        int n=s.size();  

        if(n==0) return true;  

     for(int i=0;i<n;i++)  

            {  

                if(result.empty())  

                    result.push(s[i]);  

                else if(result.top()=='('&&s[i]==')'||  

                      result.top()=='['&&s[i]==']'||  

                      result.top()=='{'&&s[i]=='}')   

                        result.pop();  

                else  

                    result.push(s[i]);  

                  

            }  

            return result.empty();  

    }  

};  

别人的思路:

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

[cpp] view
plain copy

class Solution {  

public:  

    bool isValid(string s) {  

        stack<char> paren;  

        for (char& c : s) {  

            switch (c) {  

                case '(':   

                case '{':   

                case '[': paren.push(c); break;  

                case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;  

                case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;  

                case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;  

                default: ; // pass  

            }  

        }  

        return paren.empty() ;  

    }  

};  

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

[cpp] view
plain copy

class Solution {  

public:  

    bool isValid(string s) {  

        stack<char> result;  

        for(auto & a:s){  

            if(a=='(') result.push(')');  

            else if(a=='{') result.push('}');  

            else if(a=='[')  result.push(']');  

            else if(result.empty()||result.top()!=a)//这里直接出栈判断  

                return false;  

            else result.pop();  

        }  

        return result.empty();
 

    }  

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 最长有效括号组合

动态规划:

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

\text{dp}[i]=\text{dp}[i-2]+2dp[i]=dp[i−2]+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.

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

\text{dp}[i]=\text{dp}[i-1]+\text{dp}[i-\text{dp}[i-1]-2]+2dp[i]=dp[i−1]+dp[i−dp[i−1]−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 栈

方法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())()"]
")(" -> [""]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: