forked from Mickey0521/Codility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Nesting.java
45 lines (37 loc) · 1.15 KB
/
Nesting.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
package Nesting;
// you can also use imports, for example:
import java.util.*;
class Solution {
public int solution(String S) {
// special case 1: empty string
if( S.length() ==0)
return 1;
// special case 2: odd length
else if( S.length() % 2 == 1)
return 0;
// main idea: use "stack" to check
Stack<Character> st = new Stack<>();
for(int i=0; i<S.length(); i++){
if( S.charAt(i)=='(' ){
st.push(')'); // note: push its pair (be careful)
}
else if(S.charAt(i)==')'){
// before pop: need to check if stack is empty (important)
if(st.isEmpty() == true){
return 0;
}
else{
char temp = st.pop();
if( temp != ')'){
return 0;
}
}
}
}
// be careful: if stack is "not empty" -> return 0
if( !st.isEmpty() )
return 0;
else
return 1;
}
}