题目
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.
分析
分析字符串中的括号字符是否匹配,用栈的思想就能完成,依次堆栈,遇到匹配的就出栈,最后所有的都匹配就证明正确,否则返回错误。
bool isValid(char* s) {
bool ans=true;
char * temp=(char *)malloc(sizeof(char)*10000);
int templength=0;
int slength=0;
while(s[slength]!='\0'&& ans==true)
{
if(templength==0||
(templength!=0&&(s[slength]=='('||s[slength]=='['||s[slength]=='{')))
{
temp[templength]=s[slength];
templength++;
}
else if( (temp[templength-1]=='('&&s[slength]==')') ||
(temp[templength-1]=='['&&s[slength]==']') ||
(temp[templength-1]=='{'&&s[slength]=='}'))
{
templength--;
}
else
{
ans=false;
}
slength++;
}
if(templength!=0)
ans=false;
return ans;
}