题目:
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.
解题思路:题目要求(){}[]这些要按顺序闭合。这里采用栈的思维方式。一旦遇到一个(,{,[,就将它们压入栈内,如果遇到一个 ),],}, 就将它们与栈内最上面的符号作比较,如果匹配则将栈内最顶元素压出。这个是解决按顺序闭合方面的问题。然后,还要观察这些符号左边的和右边的数量是否相等,如果不相等,还是要返回false。左边符号多,会使得读完字符串之后,栈内还有元素存在。右边符号多,会使得程序访问空栈。排除这两种情况即可。
代码如下:
class Solution {
public:
bool isValid(string s) {
char a[10000];
int count = 0;
for (int i = 0; i < s.length() ; i++) {
if (s[i] == '[') {
a[count] = '[';
count++;
}
if (s[i] == '(') {
a[count] = '(';
count++;
}
if (s[i] == '{') {
a[count] = '{';
count++;
}
if (s[i] == ')') {
if (count-1 < 0)
return false;
if (a[count-1] == '(') {
count--;
} else {
return false;
}
}
if (s[i] == ']') {
if (count-1 < 0)
return false;
if (a[count-1] == '[') {
count--;
} else {
return false;
}
}
if (s[i] == '}') {
if (count-1 < 0)
return false;
if (a[count-1] == '{') {
count--;
} else {
return false;
}
}
}
if (count == 0)
return true;
else
return false;
}
};