【Valid Parentheses】 --MyLeetCode(六)
来源:互联网 发布:mt4编程教程 编辑:程序博客网 时间:2024/06/18 11:25
Description:
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.
Note:
{ ( [ ] ) } is also vaild~~~~
Solution:
class Solution {public: bool isValid(string s) { stack<char> stk; for(char& c : s){ switch(c){ case '(': case '[': case '{': stk.push(c); break; case ')': if(stk.empty() || stk.top() != '(') return false; else stk.pop(); break; case ']': if(stk.empty() || stk.top() != '[') return false; else stk.pop(); break; case '}': if(stk.empty() || stk.top() != '{') return false; else stk.pop(); break; default: ; } } return stk.empty(); }};
1. 使用栈j将字符 '(' '{' '[' 压栈,当遇到字符 ')' '}' ']' 并且栈顶刚好匹配时,出栈。。。
2. C++11 新特性:序列for循环 ---
在C++中for循环可以使用类似java的简化的for循环,可以用于遍历数组,容器,string以及由begin和end函数定义的序列(即有Iterator)
for (int x: int_vec){ std::cout << x << endl;}
Advance Solution:
bool isValid(string s) { stack<char> temp; map<char, char> m = { {']','['},{')','('},{'}','{'} }; for (int i = 0; i < s.size(); i++) { if (s[i] == '[' || s[i] == '(' || s[i] == '{') temp.push(s[i]); else if (s[i] == ']' || s[i] == ')' || s[i] == '}') { if (temp.empty()||temp.top() != m[s[i]]) return false; else temp.pop(); } } return temp.empty();}
阅读全文
0 0
- 【Valid Parentheses】 --MyLeetCode(六)
- MyLeetCode
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- iOS 静态库使用的配置 -ObjC
- Controller的使用
- 代码干货 | 数据过滤器使用法则
- 域名备案新手百问_备案问题一站解决
- 位运算的基本方式与常用技巧
- 【Valid Parentheses】 --MyLeetCode(六)
- MySQL无法重启报错Warning: World-writable config file ‘/etc/my.cnf’ is ignored的解决方法
- js和react判断上传文件类型
- git 版本(文件)差别比较
- 压力测试工具JMeter入门教程
- socket网络编程中的ioctl()函数
- Jsp与Servlet的区别与联系
- 使用ET2000和Wireshak分析Ethercat主站的实时性
- Ubuntu 16.04 上的 NGINX Web 服务器!