LintCode: Valid Parentheses

简介:

C++

stack<char|int|string>, push(), pop(), top(), empty(), size()

复制代码
 1 class Solution {
 2 public:
 3     /**
 4      * @param s A string
 5      * @return whether the string is a valid parentheses
 6      */
 7     bool isValidParentheses(string& s) {
 8         // Write your code here
 9         stack<char> sta;
10         for (int i = 0; i < s.size(); i++) {
11             if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
12                 sta.push(s[i]);
13                 continue;
14             }
15             char top = sta.top();
16             sta.pop();
17             if (s[i] == ')' && top != '(') return false;
18             if (s[i] == ']' && top != '[') return false;
19             if (s[i] == '}' && top != '{') return false;
20         }
21         return sta.empty();
22     }
23 };
复制代码

 


本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5109518.html,如需转载请自行联系原作者

相关文章
|
canal
LeetCode 125. Valid Palindrome
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
84 0
LeetCode 125. Valid Palindrome
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
70 0
LeetCode 241. Different Ways to Add Parentheses
|
人工智能 C++
Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
763 0
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
102 0
Leetcode-Easy 20. Valid Parentheses