forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParentheses.java
57 lines (49 loc) · 1.55 KB
/
ValidParentheses.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package stack;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Created by gouthamvidyapradhan on 25/02/2017.
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.
*/
public class ValidParentheses
{
public static void main(String[] args)
{
System.out.println(hasBalancedBrackets("(h[e"));
}
private static Map<Character, Character> MAP = new HashMap<>();
// METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED
public static int hasBalancedBrackets(String str)
{
if(str == null) return 1;
MAP.put(')', '(');
MAP.put('}', '{');
MAP.put('>', '<');
MAP.put(']', '[');
Stack<Character> stack = new Stack<>();
for(int i = 0, l = str.length(); i < l; i ++)
{
switch (str.charAt(i))
{
case '(':
case '{':
case '[':
case '<':
stack.push(str.charAt(i));
break;
case ')':
case '}':
case ']':
case '>':
if(stack.isEmpty()) return 0;
char top = stack.pop();
if(top != MAP.get(str.charAt(i))) return 0;
break;
default: //ignore
}
}
return stack.isEmpty() ? 1 : 0;
}
}