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.
典型的棧的應用,直接附上代碼:
C++ code bool isValid(string s) {
stack parentheses;
for (auto c : s) {
if (c == '(' || c == '{' || c == '[')
parentheses.push(c);
else {
if (parentheses.empty())
return false;
else if (c == ')' && parentheses.top() != '(')
return false;
else if (c == ']' && parentheses.top() != '[')
return false;
else if (c == '}' && parentheses.top() != '{')
return false;
parentheses.pop();
}
}
return parentheses.empty();
}