[LeetCode] 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.

这道题让我们验证输入的字符串是否为括号字符串,包括大括号,中括号和小括号。这里我们需要用一个栈,我们开始遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回false,代码如下:

class Solution {
public:
    bool isValid(string s) {
        stack<char> parentheses;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
            else {
                if (parentheses.empty()) return false;
                if (s[i] == ')' && parentheses.top() != '(') return false;
                if (s[i] == ']' && parentheses.top() != '[') return false;
                if (s[i] == '}' && parentheses.top() != '{') return false;
                parentheses.pop();
            }
        }
        return parentheses.empty();
    }
}; 

本文转自博客园Grandyang的博客,原文链接:验证括号[LeetCode] Valid Parentheses ,如需转载请自行联系原博主。

相关文章
|
1月前
|
存储 C语言 索引
环形链表、环形链表 II、有效的括号​​​​​​​【LeetCode刷题日志】
环形链表、环形链表 II、有效的括号​​​​​​​【LeetCode刷题日志】
|
1月前
|
存储 canal 算法
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
23 0
|
3月前
leetcode-301:删除无效的括号
leetcode-301:删除无效的括号
19 0
LeetCode | 20. 有效的括号
LeetCode | 20. 有效的括号
|
3月前
|
Go
golang力扣leetcode 301.删除无效的括号
golang力扣leetcode 301.删除无效的括号
33 0
|
1月前
|
算法 安全 Java
【数据结构与算法】6、栈(Stack)的实现、LeetCode:有效的括号
【数据结构与算法】6、栈(Stack)的实现、LeetCode:有效的括号
21 0
|
2月前
|
Java
|
2月前
LeetCode题 338比特位计数,20有效的括号,415字符串相加
LeetCode题 338比特位计数,20有效的括号,415字符串相加
35 0
|
3月前
leetcode:20. 有效的括号
leetcode:20. 有效的括号
12 0
|
3月前
leetcode-856:括号的分数
leetcode-856:括号的分数
16 0

热门文章

最新文章