• Valid Parentheses

Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Solution:
1. public class Solution {
2. public boolean isValid(String s) {
3. char[] p = "(){}[]".toCharArray();
4. Map map = new HashMap<>();
5. 6. for (int i = 0; i < p.length - 1; i += 2)
7. map.put(p[i + 1], p[i]);
8. 9. Stack stack = new Stack<>();
10. 11. for (char c : s.toCharArray()) {
12. if (c == '(' || c == '{' || c == '[')
13. stack.push(c);
14. else if (stack.isEmpty() || stack.peek() != map.get(c))
15. return false;
16. else
17. stack.pop();
18. }
19. 20. return stack.isEmpty();
21. }
22. }