首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

判断括号序列是不是合法

2012-10-23 
判断括号序列是否合法括号序列,由( { [组成 例如(([{}]))()这样的序列是合法的,{)序列是不合法的。写个函数

判断括号序列是否合法

括号序列,由( { [组成 例如(([{}]))()这样的序列是合法的,{)序列是不合法的。写个函数判断该序列是否合法,函数名称为bool isValidSeq(string input);

以下是简单实现,希望有人提供更快更优的方法,

bool isValidSeq(string input)
{
     char Left[10]={0};
     int index=0;


    for (int i=0;i<input.length();++i)
   {
          if ( (input[i]=='(')
              ||(input[i]=='[')
              ||(input[i]=='{'))
         {
               Left[index++] = input[i];
   
         }
         else
        {
               if ((input[i] =='}')&&(Left[index-1]=='{'))
              {
                   Left[--index]='\0';
                   continue;
              }
           
             if ((input[i] ==']')&&(Left[index-1]=='['))
             {
                   Left[--index]='\0';
                   continue;
             }

             if ((input[i] ==')')&&(Left[index-1]=='('))
            {
                 Left[--index]='\0';
                  continue;
             }
   
       }

    }

    if (index == 0)
    {
          return true;
    }
  
 return false;

}

 

2楼cancan8538昨天 17:50
我知道可以用Stack,不知道效率是否提高了
1楼xiaoyu_93昨天 17:45
[code=cpp]n[/code]nntchar *k=new char[N];ntSqStack S;ntInitStack(S);ntcin>>k;ntint m=strlen(k);ntchar ch,e;ntwhile(m--)nt{nttch=*k++;nttif(ch==')')ntt{ntttif(*(S.top-1)!='(')nttttgoto pd;ntttelsenttttPop(S,e);ntt}nttelse if(ch==']')ntt{ntttif(*(S.top-1)!='[')nttttgoto pd;ntttelsenttttPop(S,e);ntt}nttelsentttPush(S,ch);nt}ntif(StackEmpty(S))nttprintf("匹配正确!\n");ntelsenttprintf("匹配错误!\n");
Re: xiaoyu_93昨天 17:46
回复xiaoyu_93n c语言 数据结构书上的 一个小练习. . ?

热点排行