实验二 括号匹配判断算法

题目链接<http://acm.zjnu.edu.cn/DataStruct/showproblem?problem_id=1002>

实验二 括号匹配判断算法
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2202 Accepted: 924

Description

假设在表达式中([]())或[([ ][ ])]等为正确的格式,[( ])或([( ))或 (( )])均为不正确的格式。基于栈设计一个判断括号是否正确匹配的算法。

Input

输入数据有多组,每组测试数据一行,一个字符串,只包含 ‘[‘ ,’]’ ,’(‘ ,‘)’ 。

Output

对于每组测试数据,若括号匹配输出yes,否则输出 no。

Sample Input

[]()[]
([[]])[)

Sample Output

yes
no

题解:

利用stack判断存储。从头到尾扫描一遍字符串,如果是左括号(无论是小的还是中的)都入栈。如果是右括号,就把当前的字符与栈的头元素比对,如果配对就栈跳出头元素,如果不配对,那么就可以把标记的flag设为0。如果是右括号,且栈内没有元素,则flag也可为0。如果扫描已经完毕,栈内仍然存在元素,那么flag也是0。

oj的原因多组输入不能用~scanf("")


#include <iostream>
#include <stdio.h>
#include <map>
#include <queue>
#include <string.h>
#include <string>
#include <stack>
using namespace std;
typedef long long LL;
int main(){
    char s[10005];
    stack<char>st;
    while(scanf("%s",s)!=EOF){
        while(!st.empty()) st.pop();
        int len=strlen(s),flag=1;
        for(int i=0;i<len;i++){
            if(s[i]=='('||s[i]=='[')
                st.push(s[i]);
            else{
                if(st.empty()){
                    flag=0;break;
                }
                char tmp=st.top();
                st.pop();
                if(s[i]==')'&&tmp=='['){
                    flag=0;
                    break;
                }
                else if(s[i]==']'&&tmp=='('){
                    flag=0;
                    break;
                }
            }
        }
        if(!st.empty()) flag=0;
        if(flag) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
括号匹配是指在一个字符串中,括号必须成对出现,左括号与右括号之间可能会有其他字符,但是左右括号的数量必须相等且匹配。例如,"((()))"、"()()"都是合法的括号匹配,而"((())"、")()("则不是。 基于栈的括号匹配算法的思路如下: 1. 遍历字符串中的每一个字符,如果是左括号('(', '[', '{'),则将其入栈;如果是右括号(')', ']', '}'),则需要判断栈顶元素是否与之匹配。 2. 如果栈顶元素与当前字符匹配,则将栈顶元素出栈,继续遍历下一个字符;否则括号匹配失败,返回false。 3. 如果字符串遍历结束后,栈为空,则括号匹配成功,返回true;否则括号匹配失败,返回false。 下面是使用 Python 实现基于栈的括号匹配算法的代码: ```python def is_valid_parentheses(s: str) -> bool: stack = [] mapping = {')': '(', ']': '[', '}': '{'} for c in s: if c in mapping: if not stack or stack[-1] != mapping[c]: return False stack.pop() else: stack.append(c) return not stack ``` 其中,mapping字典用于记录每个右括号与其对应的左括号。 测试用例可以包括以下几个场景: 1. 空字符串,返回True。 2. 只包含左括号或者右括号的字符串,返回False。 3. 字符串中括号不匹配的情况,返回False。 4. 字符串中括号匹配的情况,返回True。 例如: ```python assert is_valid_parentheses("") == True assert is_valid_parentheses("(") == False assert is_valid_parentheses(")") == False assert is_valid_parentheses("()") == True assert is_valid_parentheses("(()") == False assert is_valid_parentheses("()[]{}") == True assert is_valid_parentheses("([)]") == False assert is_valid_parentheses("{[]}") == True ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值