-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidParentheses.java
More file actions
38 lines (32 loc) · 1.15 KB
/
ValidParentheses.java
File metadata and controls
38 lines (32 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
// determine if the input string is valid.
// See: https://leetcode.com/problems/valid-parentheses/
package leetcode.stack;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (!map.containsKey(curr)) {
stack.push(curr);
} else if (stack.empty() || map.get(curr) != stack.pop()) {
return false;
}
}
return stack.empty();
}
public static void main(String... args) {
ValidParentheses sln = new ValidParentheses();
System.out.println(sln.isValid("()"));
System.out.println(sln.isValid("()[]{}"));
System.out.println(sln.isValid("([)]"));
System.out.println(sln.isValid("]"));
}
}