LeetCode 之 Valid Parentheses — C++ 实现
来源:互联网 发布:qq飞车鬼战刀数据 编辑:程序博客网 时间:2024/05/17 22:48
Valid Parentheses
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> hasNotMatch; int index = 0; int strLen = s.length(); if(s.empty()) //空字符串,匹配 return true; for(; index < strLen; ++index) { switch(s[index]) { //左括号直接压栈,不用比较 case '(': case '[': case '{': { hasNotMatch.push(s[index]); } break; //每出现一个右括号,匹配一次 case ')': { if(hasNotMatch.empty()) //栈空,没有待匹配德左括号 return false; if(hasNotMatch.top() == '(')//匹配,出栈 { hasNotMatch.pop(); } else return false; } break; case ']': { if(hasNotMatch.empty()) return false; if(hasNotMatch.top() == '[')//匹配,出栈 { hasNotMatch.pop(); } else return false; } break; case '}': { if(hasNotMatch.empty()) return false; if(hasNotMatch.top() == '{')//匹配,出栈 { hasNotMatch.pop(); } else return false; } break; default: break; } } if(!hasNotMatch.empty())//栈中剩有不匹配的左括号 { return false; } return true; }};
0 0
- LeetCode 之 Valid Parentheses — C++ 实现
- C实现 LeetCode->Valid Parentheses
- leetcode之Valid Parentheses
- LeetCode之Valid Parentheses
- leetcode之Valid Parentheses
- LeetCode之Valid Parentheses
- 【LeetCode】之Valid Parentheses
- 【Leetcode】之Valid Parentheses
- leetcode之Valid Parentheses
- LeetCode之Valid Parentheses
- leetcode 之 Valid Parentheses
- [C++]LeetCode: 22 Valid Parentheses
- 【leetcode c++】 20 Valid Parentheses
- Leetcode c语言-Valid Parentheses
- [LeetCode] [C++] 20. Valid Parentheses
- LeetCode 之 Valid Palindrome — C 实现
- leetcode 之 Longest Valid Parentheses
- LeetCode之Longest Valid Parentheses
- 九度OJ-题目1351:数组中只出现一次的数字
- ubuntu14.10下安装MATLAB-2013b
- 常用meta整理
- 新GRE考试阅读和老GRE阅读有哪些不同?
- 继承的概念:继承是指类与类之间的继承关系 ,子类继承父类,子类可以将父类的属性方法继承下来 网址:www.iphonetrain.com 以下代码是了车类与出租车类 共同继承了Car属性
- LeetCode 之 Valid Parentheses — C++ 实现
- 深度学习入门资料
- 内联块状元素
- 面向对象之继承
- Windows下安装scrapy
- C语言运算符优先级 详细列表
- Redis学习手册(Set数据类型)
- 并行计算复习————第三篇 并行计算理论基础:并行数值算法
- 二叉树中的那些常见的面试题