Timeline
Timeline
2025-11-18
init
Stack
Problem:
A classic stack problem. Note that at the end you need to check if the stack is empty; if it’s not empty, it’s invalid.
Code:
1234567891011121314151617181920212223242526272829303132333435 | using std::stack;using std::string;class Solution { public: bool isValid(string s) { stack<char> st; char curr; for (char &ch : s) { if (ch == '(' || ch == '[' || ch == '{') { st.push(ch); } else if (!st.empty() && ch == ')') { curr = st.top(); st.pop(); if (curr != '(') return false; } else if (!st.empty() && ch == ']') { curr = st.top(); st.pop(); if (curr != '[') return false; } else if (!st.empty() && ch == '}') { curr = st.top(); st.pop(); if (curr != '{') return false; } else { return false; } } return st.empty(); }}; |
leetcode hot 100 rewrite
123456789101112131415161718192021222324252627282930313233343536373839 | using std::string;using std::stack;class Solution { public: bool isValid(string s) { // 1 <= s.length <= 104 // s consists only of parentheses '()[]{}' stack<char> stk; char curr; for (char ch : s) { if (ch == '(' || ch == '[' || ch == '{') { stk.push(ch); } else if (!stk.empty() && ch == ')') { if (stk.top() != '(') return false; stk.pop(); } else if (!stk.empty() && ch == ']') { if (stk.top() != '[') return false; stk.pop(); } else if (!stk.empty() && ch == '}') { if (stk.top() != '{') return false; stk.pop(); } else { return false; } } return stk.empty(); }}; |
