算法课第1周第1题——20. Valid Parentheses
来源:互联网 发布:手机淘宝怎么开不了店 编辑:程序博客网 时间:2024/05/20 12:48
题目描述:
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;for (int i = 0; i < s.size();) {if (s[i] == '(' || s[i] == '[' || s[i] == '{') {a.push(s[i]);i++;}else { if (a.empty()) return false;while (!a.empty() && i < s.size()) {if ((a.top() == '(' && s[i] == ')') ||(a.top() == '[' && s[i] == ']') ||(a.top() == '{' && s[i] == '}')) {a.pop();i++;}else if (s[i] == '(' || s[i] == '[' || s[i] == '{') break;else return false;}}}if (a.empty())return true;else return false;}};
简要题解:
这题是一道利用到栈的算法题。
要匹配各个括号,首先要建立一个栈(这里命名为a),遍历字符串,每次有左括号出现,就将其放入栈中。
若遇到不是左括号(即是右括号)的字符,先判断此时栈a是否为空,若为空,说明该字符串中没有与该右括号匹配的左括号,返回false; 否则进行一个while循环操作,直到栈a为空或遍历到字符串末尾为止,不断将栈中匹配成功的左括号pop出来,当在字符串中遇到左括号时,结束while循环,继续for循环;而若遇到不与栈顶对应的右括号,则说明匹配失败,返回false.
for循环结束后,判断栈a是否为空,若为空,则全部左右括号匹配完成,返回true; 若不为空,这说明有些左括号没有右括号对应匹配,则返回false.
本题不算太难,但需要对栈的运用较为熟悉,且要有较为清晰的思路,需要充分考虑左右括号匹配的多种情况,才能完成。我有一段时间没有做算法题了,用这道题练练手,感觉还不错。之后我还会尽力做各种题来提高自己的算法水平,希望这门课能给我带来更多的收获。
0 0
- 算法课第1周第1题——20. Valid Parentheses
- leetcode第20题——*Valid Parentheses
- 【LeetCode】LeetCode——第20题:Valid Parentheses
- 第29题 Valid Parentheses
- 算法第13周Longest Valid Parentheses[hard]
- 算法课第2周第2题——241. Different Ways to Add Parentheses
- 第四周Valid Parentheses
- 第51题 Longest Valid Parentheses
- Leetcode 第20题 Valid Parentheses
- LeetCode第20题之Valid Parentheses
- valid parentheses leetcode 第20题
- leetcode 第20题<Valid Parentheses>(java)
- LeetCode算法题——20. Valid Parentheses
- leetcode 第20-21题 Valid Parentheses & Generate Parentheses
- 4.1.1—栈—Valid Parentheses
- 【leetcode】第20题 Valid Parentheses 题目+解析+代码
- 【leetcode】第32题 Longest Valid Parentheses 题目+解析+代码
- 每日一道算法题——Longest Valid Parentheses
- 关于设计模式的一些理解
- 机器翻译评价指标之BLEU
- String跟StringBuffer区别
- 疑问
- C#生成随机汉字
- 算法课第1周第1题——20. Valid Parentheses
- 258. Add Digits
- C++复合类型--引用和指针
- Spark源码解析
- linux命令认识(含例子操作)-2017-2.16
- ahalei_23
- Android 解析Xml
- 首次运行React Native时遇到的问题
- 常用的 网络协议 端口号 总结