-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
97 lines (91 loc) · 1.88 KB
/
ValidParentheses.java
File metadata and controls
97 lines (91 loc) · 1.88 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package codingInterview;
import java.util.HashMap;
import java.util.Stack;
public class ValidParentheses {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "()[][]([()])";
// boolean isValid = testValid(str);
boolean isValid = testValidWithMap(str);
System.out.println(isValid);
}
/**
* use hashmap
* @param str
* @return
*/
private static boolean testValidWithMap(String str) {
// TODO Auto-generated method stub
HashMap<Character,Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
stack.push(c);
} else if (map.values().contains(c)) {
if (!stack.isEmpty() && map.get(stack.peek()) == c) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
/**
* common approach
* @param str
* @return
*/
private static boolean testValid(String str) {
// TODO Auto-generated method stub
int length = str.length();
Stack<Character> stack = new Stack<Character>();
int i = 0;
while (i < length) {
char c = str.charAt(i);
if (stack.isEmpty()) {
stack.push(c);
} else {
switch (c) {
case '(':
if (stack.peek() == ')') {
stack.pop();
} else {
stack.push(c);
}
break;
case ')':
if (stack.peek() == '(') {
stack.pop();
} else {
stack.push(c);
}
break;
case '[':
if (stack.peek() == ']') {
stack.pop();
} else {
stack.push(c);
}
break;
case ']':
if (stack.peek() == '[') {
stack.pop();
} else {
stack.push(c);
}
break;
}
}
i++;
}
if (stack.isEmpty() && i >= length) {
return true;
}
return false;
}
}