👉 20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
class Solution {
public:
bool isValid(string s) {
stack<char> list;
bool result = false;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(' || c == '{' || c == '[') {
list.push(c);
}
if (list.empty()) {
return false;
}else if (c == ')' || c == '}' || c == ']') {
char peek = list.top();
cout << c <<", " << peek << endl;
if (c == ')' && peek == '(') {
list.pop();
} else if (c == '}' && peek == '{') {
list.pop();
} else if (c == ']' && peek == '[') {
list.pop();
} else {
return false;
}
}
}
return list.empty();
}
};