Given a string containing only (){}[], determine whether every opener has its matching closer, correctly nested.
A valid bracket string satisfies: every opener has a matching closer of the same kind, and openers close in reverse order of appearance ((()) is valid; ([)] is not).
The canonical solution is a stack: push openers, on a closer pop and compare. If the stack ends non-empty or a pop mismatches, the string is invalid.
Prints true or false.
()
true
()[]{}true
(]
false
([)]
false
Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.
pairs = {')': '(', ']': '[', '}': '{'}
s = input()
stack = []
for c in s:
if c in '([{':
stack.append(c)
else:
if not stack or stack.pop() != pairs[c]:
print('false'); exit()
print('true' if not stack else 'false')
import java.util.*;
public class Solution {
public static void main(String[] args) {
String s = new Scanner(System.in).hasNextLine() ? new Scanner(System.in).nextLine() : "";
Deque<Character> st = new ArrayDeque<>();
Map<Character, Character> pairs = Map.of(')','(',']','[','}','{');
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') st.push(c);
else if (st.isEmpty() || st.pop() != pairs.get(c)) { System.out.println("false"); return; }
}
System.out.println(st.isEmpty() ? "true" : "false");
}
}
#include <bits/stdc++.h>
using namespace std;
int main() {
string s; getline(cin, s);
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') st.push(c);
else {
if (st.empty()) { cout << "false\n"; return 0; }
char t = st.top(); st.pop();
if ((c == ')' && t != '(') || (c == ']' && t != '[') || (c == '}' && t != '{')) { cout << "false\n"; return 0; }
}
}
cout << (st.empty() ? "true" : "false") << "\n";
}
These problems solve on the same intuition — try one next while the pattern is fresh.