-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathCheckBrace.java
55 lines (43 loc) · 1.33 KB
/
CheckBrace.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
package datastructure.stack;
import org.junit.Test;
import java.util.Stack;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class CheckBrace {
/*
TASK
괄호의 유효성을 체크한다.
*/
@Test
public void test() {
assertThat(solution("(())"), is(true));
assertThat(solution("()()"), is(true));
assertThat(solution(")(())("), is(false));
assertThat(solution("(())("), is(false));
assertThat(solution(")(())"), is(false));
assertThat(solution("(()"), is(false));
assertThat(solution("())"), is(false));
assertThat(solution("(asdc;aga;ac;dsc;)"), is(true));
assertThat(solution("(aaa(bbb)ccc)"), is(true));
}
public boolean solution(String braces) {
Stack<Character> stack = new Stack<>();
if (braces == null) return true;
char open = "(".charAt(0);
char close = ")".charAt(0);
for (char c : braces.toCharArray()) {
if (c == open) {
stack.push(c);
} else if (c == close){
if (stack.isEmpty()) {
return false;
}
stack.pop();
}
}
if (stack.isEmpty()) {
return true;
}
return false;
}
}