zoukankan
html css js c++ java
堆栈小应用:配对
在“配对”问题中,栈将使问题大大简化和更富逻辑性。一个简单的例子,我们来看看如何判断表达式中的小括号是否配对。如果没有栈,这问题就不会那么美妙了。
只要你脑袋里能联想到“栈”这个词,解决方案就会变得非常简单。
遍历表达式,遇到左括号则进栈,遇到有括号则将栈顶左括号弹出,遍历完后,栈应该为空。如果不能顺利执行此过程那么表达式的括号则一定不匹配。
#include
<
iostream
>
#include
<
string
>
#include
<
stack
>
using
namespace
std;
int
main()
{
stack
<
char
>
stk;
string
exp;
bool
ok
=
true
;
cin
>>
exp;
const
int
len
=
exp.length();
for
(
int
i
=
0
; i
<
len; i
++
)
{
if
(exp[i]
==
'
(
'
)
{
stk.push(exp[i]);
}
else
if
(exp[i]
==
'
)
'
)
{
if
(
!
stk.empty())
{
stk.pop();
}
else
{
cout
<<
"
not find \'(\' for \')\' at index of
"
<<
i
<<
endl;
ok
=
false
;
}
}
}
if
(
!
stk.empty())
{
cout
<<
"
not find \')\' for \'(\'
"
<<
endl;
ok
=
false
;
}
if
(ok)
{
cout
<<
"
ok
"
<<
endl;
}
return
0
;
}
查看全文
相关阅读:
Linux命令:sed -i 解析、sed是什么、工作原理、基本语法使用、数字和正则定址、基本子命令以及最常用子命令 s 的用法
【转】putty里面的连接key文件(ppk文件)转换为xshell里面使用的key文件
【转】Go 中如何优雅关闭子进程?
[转]golang 获取本机真实IP
【转】prometheus数据写入TDengine
怎么查看redhat的版本
【转】YML是什么
[转]为什么要进行URL编码
[转]Ubuntu 上 Yarn 安装
【转】docker -v 和Dockerfile 中VOLUME 区别
原文地址:https://www.cnblogs.com/zhouyinhui/p/395117.html
最新文章
mormot2 THttpServer
mormot2 TRestHttpServer
d7 ansi和unicode相互转换
iOS内存泄漏检查&原理
监测APP卡顿
iOS7 Background Remote Notification(后台远程通知——静默push)
Kentico中UniGrid的使用
$j is not a function
Edit and replay XHR chrome/firefox etc?
XOR Gate with Truth Table in Proteus ISIS
热门文章
通用门: 与非门、或非门
卡诺图化简法详细介绍
什么是P问题、NP问题和NPC问题
nand2tetris 与 MIT6.828
Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
修改PostgreSQL字段长度导致cached plan must not change result type错误(转载)
windows主机资源Snmp OIDs CPU, Memory, Disk(转载)
springcloud禁止输出日志:ConfigClusterResolver : Resolving eureka endpoints via configuration(转载)
Supervisor 管理进程,Cloud Insight 监控进程,完美!
Spring Cloud Feign 请求添加headers(转载)
Copyright © 2011-2022 走看看