询问c++中的括号匹配

Asking about the parenthesis matching in c++

本文关键字:c++ 询问      更新时间:2023-10-16

我现在正在做我的第一个数据结构作业

主题是"括号匹配"

我心里的答案很简单,

只需将左括号推入堆栈,当遇到右括号时将其弹出。

完成我的代码后,我提交给我们学校的在线评判系统

10道题只对9道。

这是我的c++代码

是否有任何情况,我错过了这段代码??谢谢大家!

//问题问题是输入一个整数N <1000意味着测试用例

及之后的N个字符串长度<如果它是一个有效的字符串>

,应该测试1000。

如果是,输出大小写N(1~N): yes

No,输出大小写N(从1~N):No

字符串可以包含换行符

#测试用例输入

2

[] [] & lt ;>()[{}]

& lt; {>}

输出

案例1:Yes

案例2:No

#include <iostream>
#include <string>
using namespace std;
class PARENTHE
{
public:
 PARENTHE(int slength);
 ~PARENTHE();
 int StackSize() const;
 bool StackEmpty() const;
 char top() const;
 void Push(const char);
 void Pop();
private:
 char *str;
 int slength;
 int stop;
};
PARENTHE::PARENTHE(int slength)
{
    str = new char [slength];
    stop = -1;
}
PARENTHE::~PARENTHE()
{ delete [] str; }
inline int PARENTHE::StackSize() const
{ return stop+1; }
inline bool PARENTHE::StackEmpty() const
{
    return (stop == -1);
}
inline char PARENTHE::top() const
{ return str[stop]; }
void PARENTHE::Push(const char c)
{
     str[++stop] = c;
}
void PARENTHE::Pop()
{
     stop--;
}

int main()
{
    int t;
    while( cin>>t )
    {
       int i = 0;
       while( i < t )
         {
            string temp;
            cin>>temp;
            if(temp == "n")
            {
                cout<<"Case "<<++i<<": "<<"Yes"<<endl;
                break;
            }
            PARENTHE S( 1001 );
            bool check = false;
            for( int it = 0; it < temp.size() ; ++it )
            {
                if( temp[it] == '{' || temp[it] == '[' || temp[it] == '(' || temp[it] == '<' )
                    S.Push(temp[it]);
                else if ( temp[it] == '}' || temp[it] == ']' || temp[it] == '>' || temp[it] == ')' )
                {
                    if(!S.StackEmpty())
                    {
                    if(( S.top() == '{' && temp[it] == '}' ) || ( S.top() == '(' && temp[it] == ')' ) || ( S.top() == '[' && temp[it] == ']' ) || ( S.top() == '<' && temp[it] == '>' ) )
                            {
                                S.Pop();
                            }
                    else { break; }
                    }
                    else { break; }

                }
                if ( it == (temp.size()-1) && (!S.StackSize()))
                {
                   check = true;
                }
            }
            if(check)
                cout<<"Case "<<++i<<": "<<"Yes"<<endl;
            else
                cout<<"Case "<<++i<<": "<<"No"<<endl;
       }
     }
    return 0;
}

我建议你检查一下反向润色符号,它会解决你所有的问题。