题目:
栈的经典题目了,注意最后要判断栈是否为空,非空则是非法。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <string> #include <stack>
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <string> #include <stack>
using std::string; using std::stack;
class Solution { public: bool isValid(string s) { 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(); } };
|