20. Valid Parentheses
来源:互联网 发布:乐高 t r3x 编程下载 编辑:程序博客网 时间:2024/06/05 16:35
Problem:
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.
Examples:
input: []() output: true;
input: [()] ouput: true;
input: [( output: false;
这题是比较经典的栈问题,[{(都压栈,然后遇到)}]就开始匹配栈顶元素,只要不匹配则false。遍历string后,假如栈里还有元素,那么表示是缺失右元素,则false。其他情况则是true。
Code:
class Solution {public: string stack = ""; bool isValid(string s) { for (int i = 0; i < s.length(); i++) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') { stack += s[i]; } else { if (!isMatch(stack[stack.length() - 1], s[i])) { return false; } else { stack.erase(stack.end()-1, stack.end()); } } } if (stack.length() == 0) { return true; } else { return false; } } bool isMatch(char c1, char c2) { if ((c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}') || (c1 == '[' && c2 == ']')) { return true; } return false; }};
阅读全文
1 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 20.Valid Parentheses
- 20.Valid Parentheses
- 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 20. Valid Parentheses
- 20. Valid Parentheses
- 前端路由 -- vue-router
- 算法 1.4.17
- Timer
- CF #433 DIV2 B. Maxim Buys an Apartment
- 说说云盘背后的黑科技!
- 20. Valid Parentheses
- 使用cmake gui 生成cpp-netlib vs2013项目并编译说明
- linux grep
- springMVC类型转换,提交日期字符数据自动转换日期格式
- NodeJs surperagent API
- 慕课笔记--[课程]Node.js+MongoDB建站攻略
- 爬取12306站点信息
- DBV-00201: Block, DBA 21065723, marked corrupt for invalid redo application解决
- amoy url