Skip to content

[LeetCode] 20. 有效的括号 #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Aug 11, 2019 · 0 comments
Open

[LeetCode] 20. 有效的括号 #39

Animenzzzz opened this issue Aug 11, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

解题思路:使用栈,匹配出栈,比较简单

C++解题

class Solution {
public:
    bool isValid(string s) {
        stack <string> ss;
        for (int i = 0; i < s.size(); i++)
        {
            string sub = s.substr(i,1);
            if (sub == ")")
            {
                if(ss.empty()) return false;
                if(ss.top() == "(") ss.pop();
                else return false;
            }else if(sub == "}"){
                if(ss.empty()) return false;
                if(ss.top() == "{") ss.pop();
                else return false;
            }else if(sub == "]"){
                if(ss.empty()) return false;
                if(ss.top() == "[") ss.pop();
                else return false;
            }else{
                string sub11 = s.substr(i,1);
                ss.push(sub11);
            }
        }
        if(!ss.empty()) return false;
        return true;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant