7-1 括号匹配

给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。

输入格式:

输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。

输出格式:

如果括号配对,输出yes,否则输出no。

输入样例1:

sin(10+20)

输出样例1:

yes

输入样例2:

{[}]

输出样例2:

no

一、 算法:

Status Matching()
{
InitStack(S);
flag = 1;
cin >> ch;
while(ch!='#' && flag)
{
switch(ch)
{
case '[' || '(':
Push(S, ch);
break;
case ')':
if(!StackEmpty(S) && GetTop(S)=='(')
Pop(S, x);
else flag = 0;
break;
case ']':
if(!StackEmpty(S) && GetTop(S)=='[')
Pop(S, x);
else flag = 0;
break;
}
cin >> ch;
}
if(StackEmpty(S) && flag) return true;
else return false;
}

二、具体实现代码

#使用STL的stack容器 

#include <iostream>
#include <stack>
using namespace std;
bool Matching(string a);
int main()
{
    string str;
    getline(cin,str);
    if(Matching(str)) cout<<"yes";
    else cout<<"no";
    return 0;
}
bool Matching(string str)
{
    stack<char> s;
    int flag=1;
    int i=0;
    while(flag==1&&str[i]!='\0'){
        char ch = str[i];
        if(ch=='('||ch=='{'||ch=='[')      //遇到左括号则入栈
            s.push(ch);
        else if(ch==')'||ch=='}'||ch==']')
        {
            if(s.empty()) flag = 0;        //遇到右括号同时栈为空,不匹配
            else
            {
                char e=s.top();
                s.pop();                   //遇到右括号且栈不为空,出栈
                if(ch==')'&&e!='('||ch=='}'&&e!='{'||ch==']'&&e!='['){
                    flag=0;}
            }
        }
        i++;   
    }
    if(flag==1&&s.empty()) return true;
    else return false;
}

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值