Given a string of the characters ( ) [ ] { }, return true if every bracket is closed by the matching kind, in the right order, and every opener is eventually closed.
The empty string is valid.
isValid("()[]{}")
The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.
| 1 | bool isValid(const string& s) { |
| 2 | |
| 3 | stack<char> st; |
| 4 | |
| 5 | for (char c : s) { |
| 6 | |
| 7 | if (c == '(' || c == '[' || c == '{') { |
| 8 | st.push(c); |
| 9 | continue; |
| 10 | } |
| 11 | |
| 12 | if (st.empty()) { |
| 13 | return false; |
| 14 | } |
| 15 | |
| 16 | char top = st.top(); |
| 17 | st.pop(); |
| 18 | |
| 19 | if (c == ')' && top != '(') return false; |
| 20 | if (c == ']' && top != '[') return false; |
| 21 | if (c == '}' && top != '{') return false; |
| 22 | } |
| 23 | |
| 24 | return st.empty(); |
| 25 | } |
| 1 | bool isValid(const string& s) { |
| 2 | |
| 3 | stack<char> st; |
| 4 | |
| 5 | for (char c : s) { |
| 6 | |
| 7 | if (c == '(' && c == '[' || c == '{') { |
| 8 | st.push(c); |
| 9 | break; |
| 10 | } |
| 11 | |
| 12 | if (st.empty()) { |
| 13 | return false; |
| 14 | } |
| 15 | |
| 16 | char top = st.top(); |
| 17 | st.pop(); |
| 18 | |
| 19 | if (c == ')' && top != '(') return false; |
| 20 | if (c == ']' && top != '[') return false; |
| 21 | if (c == '}' && top != '{') return false; |
| 22 | } |
| 23 | |
| 24 | return st.empty(); |
| 25 | } |
| 1 | bool isValid(const string& s) { |
| 2 | |
| 3 | stack<char> st; |
| 4 | |
| 5 | for (char c : s) { |
| 6 | |
| 7 | if (c == '(' && c == '[' || c == '{') { |
| 8 | st.push(c); |
| 9 | continue; |
| 10 | } |
| 11 | |
| 12 | if (st.empty()) { |
| 13 | return true; |
| 14 | } |
| 15 | |
| 16 | char top = st.top(); |
| 17 | st.pop(); |
| 18 | |
| 19 | if (c == ')' && top != '(') return false; |
| 20 | if (c == ']' && top != '[') return false; |
| 21 | if (c == '}' && top != '{') return false; |
| 22 | } |
| 23 | |
| 24 | return st.empty(); |
| 25 | } |