栈的运用( Valid Parentheses)

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

猜你喜欢

转载自blog.51cto.com/13925487/2160956
今日推荐