题目描述【Leetcode】
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) {
stack<char>br;
for(int i = 0; i < s.length(); i++){
if(s[i] == '[' || s[i] == '(' || s[i] == '{') br.push(s[i]);
else if(s[i] == ']' && !br.empty() && br.top() == '[') br.pop();
else if(s[i] == ')' && !br.empty() && br.top() == '(') br.pop();
else if(s[i] == '}' && !br.empty() && br.top() == '{') br.pop();
else return false;
}
if(br.size() == 0) return true;
else return false;
}
};