1. 程式人生 > >棧的運用( Valid Parentheses)

棧的運用( Valid Parentheses)

valid empty turn bool == sed null ont ets

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)