Leetcode[20]-Valid Parentheses
2015-06-11 14:45
288 查看
Given a string containing just the characters
The brackets must close in the correct order,
思路:借助vector容器,存放字符’(‘,’{‘,’[‘,从左到右的读取字符串的每一个字符,
如果字符为上面给定的三个,则加入到vector中;
如果不是,在确保vector容器有字符的情况下,则让其和vector的最后一个比较;
如果是匹配的,则将vector容器的大小缩减为size()-1;
如果不匹配,则返回false;
最后,如果vector元素全部匹配完了,则返回true,否则返回false;
代码如下(c++):
'(', ')',
'{', '}',
'[' and ']', determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are all valid but
"(]"and
"([)]"are not.
思路:借助vector容器,存放字符’(‘,’{‘,’[‘,从左到右的读取字符串的每一个字符,
如果字符为上面给定的三个,则加入到vector中;
如果不是,在确保vector容器有字符的情况下,则让其和vector的最后一个比较;
如果是匹配的,则将vector容器的大小缩减为size()-1;
如果不匹配,则返回false;
最后,如果vector元素全部匹配完了,则返回true,否则返回false;
代码如下(c++):
class Solution { public: bool isValid(string s) { vector<char> str; int len = s.length(); for(int i=0; i<len; i++){ if(isThose(s[i])) { str.push_back(s[i]); continue; } if(str.size()>0 && isTrue(str[str.size()-1],s[i])) { cout<<str.size()<<"f"<<isTrue(str[str.size()-1],s[i])<<endl; str.resize(str.size()-1); }else{ return false; } } if(str.size() == 0) return true; else return false; } bool isThose(char &a){ if(a == '{' || a == '(' || a == '[')return true; return false; } bool isTrue(char &a, char &b){ if( a == '(' && b == ')' ) return true; else if( a == '[' && b == ']' ) return true; else if( a == '{' && b == '}' ) return true; return false; } };
相关文章推荐
- Nginx 负载均衡
- JSP基本语法
- leetcode Ch2-Dynamic Programming II
- swift 用GCD写的倒计时 防止计时器不准
- 关于Q3ListView的排序功能
- nodejs 学习资料
- 纯lua版A*算法优化测试
- NFS
- 距离汇总
- Android项目开发前的准备工作
- iOS ARC下dealloc过程及.cxx_destruct的探究
- [歪谈]为什么项目经理是很难有节操的选举
- 悲剧!Homebrew 的作者被 Google 拒啦,因为他不会翻转二叉树(转自V2EX)
- 挨踢人生路
- [Windows编程] Windows最常见的数据类型列表
- Apache Shiro 使用手册(五)Shiro 配置说明
- 【iOS官方文档翻译】iOS的蓝牙连接、数据接收及发送
- Zookeeper问题排查
- 自定义RatingBar 评分控件
- 挨踢人生路