Valid Parentheses
Tags: leetcode, 算法
1. 题目
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.
2. 解答
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> chStack;
for (string::size_type i = 0; i < s.size(); ++i) {
switch (s[i]) {
case '(':
case '{':
case '[' :
chStack.push(s[i]);
break;
case ')':
if (chStack.empty() || chStack.top() != '(') {
return false;
}
chStack.pop();
break;
case '}':
if (chStack.empty() || chStack.top() != '{') {
return false;
}
chStack.pop();
break;
case ']':
if (chStack.empty() || chStack.top() != '[') {
return false;
}
chStack.pop();
break;
default:
return false;
}
}
if (chStack.empty()) {
return true;
}
return false;
}
};