LeetCode20:Valid Parentheses
来源:互联网 发布:kali linux树莓派 编辑:程序博客网 时间:2024/05/29 10:49
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.
#include<iostream>#include<algorithm>#include<stack>using namespace std;//使用压栈的方式解决,题目中还有一种valid情况没有说明,需要我们自己考虑的,就是"({[]})"这种层层嵌套但//可以完全匹配的,也是valid的一种。解题思路是这样的:我们对字符串S中的每一个字符C,如果C不是右括号,//就压入栈stack中。如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回not valid,//非空就取出栈顶的字符pre来对比,如果是匹配的,就弹出栈顶的字符,继续取S中的下一个字符;//如果不匹配,说明不是valid的,直接返回。当我们遍历了一次字符串S后,注意这里还有一种情况,//就是stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的,//因为只要valid,一定全都可以得到匹配使左括号弹出。class Solution{public:bool isValid(string s){stack<char> stackchar;if (s == "") return false;int i = 0;while(i != s.length()){char c =s[i];if ((c != ')') && (c != ']') && (c != '}')) //字符串S中的每一个字符,如果不是右括号,就压入栈stack中{stackchar.push(c);}else{if (stackchar.size()==0) //如果C是右括号,判断stack是不是空的,空则说明没有左括号,直接返回return false;char pre = stackchar.top(); //非空就取出栈顶的字符pre来对比,如果是匹配的,就弹出栈顶的字符switch (c){case ')': if (pre == '(')stackchar.pop();elsereturn false;break;case ']': if (pre == '[')stackchar.pop();elsereturn false;break;case '}': if (pre == '{')stackchar.pop();elsereturn false;break;}}++i; //继续取S中的下一个字符}//遍历字符串s结束后,如果stack中还有残留的字符没有得到匹配,即此时stack不是空的,这时说明S不是valid的if (stackchar.size() == 0) return true;elsereturn false;}};
0 0
- LeetCode20: Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode20-Valid Parentheses
- LeetCode20:Valid Parentheses
- LeetCode20:Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20 Valid Parentheses
- LeetCode20. Valid Parentheses
- Leetcode20: Valid Parentheses
- Leetcode20. Valid Parentheses
- leetcode20:Valid Parentheses
- LeetCode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 【LeetCode20】【Valid Parentheses】
- Leetcode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 强大的STL之set
- 数字三角形问题
- 两个栈实现一个队列
- 日经春秋 20151118
- spring mvc 传中文 到controller层乱码的 解决方法
- LeetCode20:Valid Parentheses
- InputStreamReader FileReader
- 【Treap】[CQBZOJ2803]普通平衡树
- CSS:关于“-webkit-appearance: none”样式使用问题
- UITabBarController
- std::shared_ptr简介
- vector的resize()和reserve()函数的区别
- 装饰者模式——HeaderFirst学习笔记
- CSS3画图2