询问c ++中的括号匹配

时间:2014-03-21 06:58:48

标签: c++ stack

我目前正在处理我的第一个数据结构作业

主题是"括号匹配"

我心中的答案很简单,

只需将左括号推到堆栈,当你遇到右括号时就弹出它。

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

在10个问题中只能得到9个纠正。

这是我的c ++代码

我在这段代码中遗漏了什么情况?谢谢大家!

/ 问题 / 问题是输入整数N <1。 1000表示测试用例

并且跟随N个字符串长度&lt;如果1000是有效的字符串,则应测试1000

如果是,输出案例N(从1~N):是

否,输出案例N(从1~N):否

字符串可能包含换行符

#Test个案

输入

2

[] []&LT;&GT;()[{}]

&LT; {&GT;}

输出

案例1:是

案例2:否

#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;
}

1 个答案:

答案 0 :(得分:0)

我建议您查看reverse polish notation,它会处理您的所有问题。