forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdalma.kt
More file actions
42 lines (36 loc) · 1.06 KB
/
Copy pathjdalma.kt
File metadata and controls
42 lines (36 loc) · 1.06 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
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import java.util.Deque
import java.util.ArrayDeque
class `valid-parentheses` {
/**
* 괄호의 쌍을 Stack을 활용하여 검증한다.
* TC: O(n), SC: O(n)
*/
fun isValid(s: String): Boolean {
if (s.length % 2 != 0) return false
val parentheses = mapOf(
'(' to ')',
'{' to '}',
'[' to ']'
)
val stack: Deque<Char> = ArrayDeque()
for (char in s) {
if (parentheses.containsKey(char)) {
stack.push(char)
} else if (stack.isEmpty() || parentheses[stack.pop()] != char){
return false
}
}
return stack.isEmpty()
}
@Test
fun `입력한 문자열의 괄호의 열림과 닫힘을 검증한다`() {
isValid("()") shouldBe true
isValid("{()}") shouldBe true
isValid("(){}[]") shouldBe true
isValid("{(}") shouldBe false
isValid("){") shouldBe false
}
}