Balanced Bracket Sequence (Valid Parentheses)
Problem
Given a string containing just the characters (, ), {, }, [, and ], determine if the input string is valid — every opening bracket must be closed by the same type of bracket, in the correct order.
Example:
Input: "{[()]}"
Output: true
Input: "{[(])}"
Output: false
Code
import java.util.*;
public class ValidParentheses {
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
Map<Character, Character> pairs = new HashMap<>();
pairs.put(')', '(');
pairs.put('}', '{');
pairs.put(']', '[');
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty() || stack.pop() != pairs.get(c)) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isValid("{[()]}"));
System.out.println(isValid("{[(])}"));
}
}def is_valid(s):
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for c in s:
if c in "({[":
stack.append(c)
else:
if not stack or stack.pop() != pairs[c]:
return False
return not stack
print(is_valid("{[()]}"))
print(is_valid("{[(])}"))