LeetCode 20. Valid Parentheses
2017-04-10 15:16
405 查看
题目描述:
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.
思路:
利用也栈的后进先出,相当于就是如果相邻两个有匹配,就从栈中出来,不匹配就放入栈,直到找到匹配的。具体思路见代码注释。
代码:
输出结果: 3ms
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) { stack<char> a;//用来进行处理的char型栈 int len = s.length();//计算s的长度 for (int i = 0; i < len; ++i){//从第一个开始遍历字符串s if (a.size() == 0){//如果栈a没有元素 a.push(s[i]);//将当前的s[i]放入a,继续循环下一个元素 continue; } if (a.top() == '('){//如果当前栈a的顶为'(' if (s[i] == ')'){//如果当前的s[i]为')',即与题中要求匹配 a.pop();//将栈a顶弹出 } else{//否则将当前s[i]放入a a.push(s[i]); } } else if (a.top() == '['){//如果当前栈a的顶为'['同理 if (s[i] == ']'){ a.pop(); } else{ a.push(s[i]); } } else if (a.top() == '{'){//如果当前栈a的顶为'{'同理 if (s[i] == '}'){ a.pop(); } else{ a.push(s[i]); } } } return bool(!a.size());//返回bool(!a.size),如果最终a的size为0,则满足;否则不满足 } };
输出结果: 3ms
相关文章推荐
- leetcode--20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- [C++]LeetCode 20: Valid Parentheses(判断运算符有效性)
- [Leetcode] 20 - Valid Parentheses
- [leetcode]20. Valid Parentheses
- LeetCode---(20)Valid Parentheses
- Java [leetcode 20]Valid Parentheses
- LeetCode20. Valid Parentheses
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode20 Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode:20 Valid Parentheses-每日编程第三十七题
- leetcode——20——Valid Parentheses
- [LeetCode]--20. Valid Parentheses
- [LeetCode]20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode 20 - Valid Parentheses
- leetcode: 20. Valid Parentheses