public class Bracket {
public static void main(String[] args) {
String str = "[()]";
System.out.println(isValid(str));
}
// [()]
public static boolean isValid(String str) {
Stack<Character> stack = new Stack<>();
Map<Character, Character> map = new HashMap<Character, Character>();
map.put(')', '(');
map.put('}', '{');
map.put(']', '[');
char[] chs = str.toCharArray();
for (Character ch : chs) {
if (!map.containsKey(ch)) {
stack.push(ch);
} else {
Character item = map.get(ch);
if (stack.isEmpty() || !item.equals(stack.pop())) {
return false;
}
}
}
return stack.isEmpty();
}
}