-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathBrackets.java
52 lines (46 loc) · 1.46 KB
/
Brackets.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
package Brackets;
// you can also use imports, for example:
import java.util.*;
class Solution {
public int solution(String S) {
// main idea: use "Stack" (push and pop)
//special case
if(S.length() == 0)
return 1;
// new Stack<Character>()
Stack<Character> stack = new Stack<>();
// scan the string (just one pass)
for(int i=0; i< S.length(); i++){
// note: push "its pair"
if( S.charAt(i) == '(' ){
stack.push(')');
}
else if( S.charAt(i) == '[' ){
stack.push(']');
}
else if( S.charAt(i) == '{' ){
stack.push('}');
}
// pop and check
else if( S.charAt(i) == ')' || S.charAt(i) == ']' || S.charAt(i) == '}'){
// important: check if the stack is empty or not (be careful)
if(stack.isEmpty() == true){
return 0;
}
else{
char temp = stack.pop(); // check if the stack is empty before pop!!!
if(temp != S.charAt(i)){ // not a pair
return 0;
}
}
}
}
// note: check if the stack is empty or not (be careful)
if( !stack.isEmpty() ){
return 0;
}
else{
return 1;
}
}
}