注册 登录
编程论坛 C++教室

PTA上的一道括号匹配检测题目,有两个检测点过不去,是有哪些没考虑到的问题吗?(附上题目和代码)

Umbrella_YX 发布于 2020-12-23 13:24, 2219 次点击
只有本站会员才能查看附件,请 登录
只有本站会员才能查看附件,请 登录


程序代码:
#include<cstdio>
#include<cstdlib>
#include<stack>
#include<cstring>
using namespace std;
int main(){
    char str[110];
    stack<char> stk;
    fgets(str, 110, stdin);
    str[strcspn(str, "\n")] = 0;
    int n = 0;
    int i = 0;
    while(str[i]!='\0'){
        if(str[i]=='(' || str[i]=='[' || str[i]=='{'){                 //遇见左括号进栈     
            stk.push(str[i]);
        }
        else if(str[i]==')' || str[i]==']' || str[i]=='}'){            //遇见右括号匹配
            if(stk.empty()){                                          //栈为空无法匹配的情况
                i++;
                continue;
            }
            else{                                                     //栈不为空,左右对应可匹配的情况
                if(str[i]==')' && stk.top()=='('){
                    stk.pop();
                    n++;
                }
                else if(str[i]==']' && stk.top()=='['){
                    stk.pop();
                    n++;
                }
                else if(str[i]=='}' && stk.top()=='{'){
                    stk.pop();
                    n++;
                }
                else{                                                //栈不为空,左右不对应不可匹配的情况
                    i++;
                    continue;
                }
                    
            }
        }
        i++;
    }
    printf("%d\n",n);
}
4 回复
#2
rjsp2020-12-23 14:36
程序代码:
#include <cstdio>
#include <stack>
using namespace std;

int main( void )
{
    char str[102];
    stack<char> stk;
    fgets( str, sizeof(str), stdin );

    size_t count = 0;
    for( size_t i=0; str[i]; ++i )
    {
        if( str[i]=='(' || str[i]=='[' || str[i]=='{' )
            stk.push( str[i] );
        else if( str[i] == ')' )
        {
            if( stk.empty() || stk.top()!='(' )
            {
                count = 0;
                break;
            }
            stk.pop();
            ++count;
        }
        else if( str[i] == ']' )
        {
            if( stk.empty() || stk.top()!='[' )
            {
                count = 0;
                break;
            }
            stk.pop();
            ++count;
        }
        else if( str[i] == '}' )
        {
            if( stk.empty() || stk.top()!='{' )
            {
                count = 0;
                break;
            }
            stk.pop();
            ++count;
        }
    }
    if( !stk.empty() )
        count = 0;

    printf( "%zu\n", count );
}
#3
Umbrella_YX2020-12-23 15:13
回复 2楼 rjsp
嗯,谢谢版主,代码放进pta没问题,但我有点不理解这一部分的思路是什么
只有本站会员才能查看附件,请 登录
#4
rjsp2020-12-23 15:37
如果 栈是空的,或栈顶数据不是'(',那么就是括号不匹配,按题目要求可以退出循环输出0了
#5
Umbrella_YX2020-12-23 15:58
回复 4楼 rjsp
我一直以为要遍历完,原来出现这种情况就可以直接输出0了,那我连题目的意思都没理解清楚,现在明白了,谢谢
1