要求

  • 给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效
  • 左括号必须用相同类型的右括号闭合
  • 左括号必须以正确的顺序闭合
  • 空字符串可被认为是有效字符串

思路

  • 遇到左方向括号入栈,遇到右方向括号查看栈顶元素,匹配则出栈
  • 遍历结束后栈为空则满足匹配原则

实现

 1 #include<iostream>
2 #include<stack>
3 #include<cassert>
4
5 using namespace std;
6
7 class Solution{
8 public:
9 bool isValid(string s){
10
11 stack<char> stack;
12 for( int i = 0 ; i < s.size() ; i ++ ){
13 if( s[i] == '(' || s[i] == '{' || s[i] == '[')
14 stack.push( s[i] );
15 else{
16
17 if( stack.size() == 0)
18 return false;
19
20 char c = stack.top();
21 stack.pop();
22
23 char match;
24 if( s[i] == ')')
25 match = '(';
26 else if( s[i] == ']' )
27 match = '[';
28 else{
29 assert( s[i] == '}' );
30 match = '{';
31 }
32
33 if( c != match)
34 return false;
35 }
36 }
37
38 if( stack.size() != 0 )
39 return false;
40
41 return true;
42 }
43 };
44
45 void printBool(bool res){
46 cout << (res ? "True" : "False") << endl;
47 }
48
49 int main(){
50
51 printBool(Solution().isValid("()"));
52 printBool(Solution().isValid("()[]{}"));
53 printBool(Solution().isValid("(]"));
54 printBool(Solution().isValid("([)]"));
55
56 return 0;
57 }

最新文章

  1. event
  2. iOS 自定义Actionsheet
  3. aspx后台页面添加服务器控件
  4. What are the advantages of logistic regression over decision trees?FAQ
  5. Final对象
  6. C++朝花夕拾【更新】
  7. [转]A Faster UIWebView Communication Mechanism
  8. 简单的led驱动程序设计
  9. 用yii2给app写接口(下)
  10. java 查找类的所有子类
  11. MongoDB、PyMongo数据操作
  12. Android为TV端助力 EventBus.getDefault()开源框架
  13. 安装zookeeper遇到的问题
  14. Python Socket 通信
  15. XMPP serverejabberd-14.12本地搭建
  16. ZooKeeper学习之路 (五)ZooKeeper API的简单使用 增删改查
  17. vue生命周期和react生命周期对比
  18. DBGrid相关技术整理
  19. EF框架的优点是什么?
  20. 开源PCRF、PCRF体验与PCRF实现

热门文章

  1. kubernetes使用statefulset部署mongoDB 单机版 自定义配置文件、密码等
  2. Distributed | MapReduce
  3. Apache Hudi 0.8.0版本重磅发布
  4. 如何获取canvas当前的缩放值
  5. day-4 xctf-pwn CGfsb
  6. Windows命令行学习(系统信息收集)
  7. Spring Boot+MySQL+Spring Data JPA一个Web的Demo
  8. Java面向对象OOP思想概述
  9. 在kubernetes上部署zookeeper,kafka集群
  10. 文件上传bypass jsp内容检测的一些方法