20. Valid Parentheses
Input: "()"
Output: trueInput: "()[]{}"
Output: trueInput: "(]"
Output: falseInput: "([)]"
Output: falseInput: "{[]}"
Output: trueLast updated
Input: "()"
Output: trueInput: "()[]{}"
Output: trueInput: "(]"
Output: falseInput: "([)]"
Output: falseInput: "{[]}"
Output: trueLast updated
bool isValid(string s) { // time: O(n); space: O(n)
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else { // c == ')' || c == ']' || c == '}'
if (st.empty() ||
(c == ')' && st.top() != '(') ||
(c == ']' && st.top() != '[') ||
(c == '}' && st.top() != '{')) return false;
st.pop();
}
}
return st.empty();
}