您的位置:首页 > 其它

leetcode 20. Valid Parentheses

2016-05-26 09:18 381 查看

题目:

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) {
//构造一个堆栈,存放s
int len=strlen(s);

if(len==0)
return true;

char * stack=(char *)malloc(sizeof(char)*len);
int top=0;

int i;
for(i=0;i<len;i++)
{
if(top==0)
{
stack[top]=s[i];
top++;
}
else//top>0时
{
if( (stack[top-1] == '(' && s[i]==')') || (stack[top-1]=='[' && s[i]==']') || (stack[top-1]=='{' && s[i]=='}') )
{
top--;
}
else
{
stack[top]=s[i];
top++;
}
}

}

if(top==0)
return true;
else
return false;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: