题目:
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.
思路:
一个简单的词法分析器,利用栈即能实现括号的匹配。
代码:
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char* stack = new char[100];
int top = 0;
for(int i = 0; i < s.size(); i++)
{
char c = s[i];
if(top > 0 && valid(stack[top - 1], s[i]))
{
top--;
}
else
{
stack[top++] = s[i];
}
}
return top == 0;
}
bool valid(char c1, char c2)
{
if(c1 == '(' && c2 == ')')
{
return true;
}
else if(c1 == '[' && c2 == ']')
{
return true;
}
else if(c1 == '{' && c2 == '}')
{
return true;
}
else
{
return false;
}
}
};