题目:Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
开辟一个数组空间当做堆栈,“{”, “(” ,“【” 这类左边的字符,如果右边没有直接匹配的字符,就直接入堆栈存储;如果有匹配的就原始数组的下标直接加2;
遇到“}”, “】” ,“)”这些右边的字符,就直接和堆栈中的比较,如果不匹配就返回false;否则原始数组和堆栈的下标继续。
代码:
bool isValid(char* s) {
int i=0;
int length=strlen(s);
int sub=-1;
// 申请空间
char* stack=(char*)malloc(sizeof(char)*length);
printf("The length iss %d\n",length);
if(length%2 != 0 || length==0 )
{
printf("The length %d\n",length);
return false;
}
while(s[i]!='\0' && i< length)
{
//printf("The %c %c \n",s[i],s[i+1]);
int mark=0;
switch(s[i])
{
case '(':
if(s[i+1] == '\0')
return false;
else if(s[i+1] != ')')
mark=1;
break;
case '[':
if(s[i+1] == '\0')
return false;
else if(s[i+1] != ']')
mark=1;
break;
case '{':
if(s[i+1] == '\0')
return false;
else if(s[i+1] != '}')
mark=1;
break;
case ')':
if(stack[sub] != '(')
return false;
else
mark=2;
break;
case '}':
if(stack[sub] != '{')
return false;
else
mark=2;
break;
case ']':
if(stack[sub] != '[')
return false;
else
mark=2;
break;
default:
printf("Default\n");
break;
}
if(mark==1)
{
printf("The mark ==1\n");
stack[++sub]=s[i++];
}
else if(mark==2)
{
printf("The mark ==2\n");
--sub;
i++;
}
else
{
printf("The mark\n");
i+=2;
}
}
return true;
}