[刷题] 20 Valid Parentheses
2024-10-07 00:21:19
要求
- 给定一个只包括
'('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效 - 左括号必须用相同类型的右括号闭合
- 左括号必须以正确的顺序闭合
- 空字符串可被认为是有效字符串
思路
- 遇到左方向括号入栈,遇到右方向括号查看栈顶元素,匹配则出栈
- 遍历结束后栈为空则满足匹配原则
实现
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 }
最新文章
- event
- iOS 自定义Actionsheet
- aspx后台页面添加服务器控件
- What are the advantages of logistic regression over decision trees?FAQ
- Final对象
- C++朝花夕拾【更新】
- [转]A Faster UIWebView Communication Mechanism
- 简单的led驱动程序设计
- 用yii2给app写接口(下)
- java 查找类的所有子类
- MongoDB、PyMongo数据操作
- Android为TV端助力 EventBus.getDefault()开源框架
- 安装zookeeper遇到的问题
- Python Socket 通信
- XMPP serverejabberd-14.12本地搭建
- ZooKeeper学习之路 (五)ZooKeeper API的简单使用 增删改查
- vue生命周期和react生命周期对比
- DBGrid相关技术整理
- EF框架的优点是什么?
- 开源PCRF、PCRF体验与PCRF实现
热门文章
- kubernetes使用statefulset部署mongoDB 单机版 自定义配置文件、密码等
- Distributed | MapReduce
- Apache Hudi 0.8.0版本重磅发布
- 如何获取canvas当前的缩放值
- day-4 xctf-pwn CGfsb
- Windows命令行学习(系统信息收集)
- Spring Boot+MySQL+Spring Data JPA一个Web的Demo
- Java面向对象OOP思想概述
- 在kubernetes上部署zookeeper,kafka集群
- 文件上传bypass jsp内容检测的一些方法