码迷,mamicode.com
首页 > 其他好文 > 详细

栈的运用( Valid Parentheses)

时间:2018-08-17 16:29:59      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:char*   parent   code   null   sam   pre   空间   str   character   

Given a string containing just the characters ‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘ and ‘]‘, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

bool isValid(char* s) {

int k=0,i=0;
int p;
p=strlen(s);
int MAXSIZE=10000;//输入较大时,可能空间不足

char st;
st=(char
)malloc(MAXSIZE*sizeof(char));

if(s==NULL)
return true;
if(p%2==1)
return false;
while(s[k]){
if((s[k]==‘{‘)||(s[k]==‘[‘)||(s[k]==‘(‘)){
st[i]=s[k];
++k;
++i;}
else{
switch(s[k]){
case ‘}‘:{
if(st[i-1]==‘{‘)//注意比较的数组以及序号
--i;
else
return false;
++k;

      break;}
       case ‘]‘:{
              if(st[i-1]==‘[‘)
                  --i;
      else 
          return false;
            ++k;
      break;}
       case ‘)‘:{
              if(st[i-1]==‘(‘)
                  --i;
      else 
          return false;

        ++k;    
      break;}
  }
 }

}
if(i==0)
return true;
else
return false;
}

栈的运用( Valid Parentheses)

标签:char*   parent   code   null   sam   pre   空间   str   character   

原文地址:http://blog.51cto.com/13925487/2160956

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!