题目链接: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.
(1)思路:这和数据结构课本上Stack的括号匹配例题类似,只不过括号的类型有三种。遇到左括号直接入栈,遇到右括号进行匹配,匹配成功的左括号弹出栈,匹配不成功或最后栈不为空返回 false。
(2)代码:
class Solution {
public:
bool isValid(string s) {
char* stackBot = (char*) malloc(s.length());
int i;
int stacktop = -1;
for (i = 0; i < s.length(); ++i) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') stackBot[++stacktop] = s[i];
else if ((s[i] == ')' && stackBot[stacktop] == '(') || (s[i] == ']' && stackBot[stacktop] == '[') || (s[i] == '}' && stackBot[stacktop] == '{')) --stacktop;
else {
free(stackBot);
return 0;
}
}
free(stackBot);
return stacktop == -1;
}
};