[LeetCode] Valid Parentheses

boooookreeeed·2025년 1월 8일

https://leetcode.com/problems/valid-parentheses/description/

총평: 문제 자체는 익숙했지만 kotlin에 익숙하지 않아서 어려웠다.

class Solution {
    fun isValid(s: String): Boolean {
        val stack = Stack<Char>()
        val bracketMap = mapOf(')' to '(', '}' to '{', ']' to '[')

        for (char in s) {
            if (char in bracketMap.values) { // If it's an opening bracket
                stack.push(char)
            } else if (char in bracketMap.keys) { // If it's a closing bracket
                if (stack.isEmpty() || stack.peek() != bracketMap[char]) {
                    return false
                }
                stack.pop()
            }
        }

        return stack.isEmpty()
    }
}

char과 String

s: String일 때
for (char in s)로 받을 수 있다.

Stack

java.util.Stack

val stack = Stack<Int>()

stack.push(3)
stack.add(0, 10) // index 지정하여 삽입
stack.peek() // top 확인
stack.size
stack.pop()
stack.isEmpty()

add를 사용할거면 굳이 stack을 쓸 필요가 없음

quote in kotlin

double quotes ("") String
single quotes ('') Char

map in kotlin

keys are unique, values can be duplicated
Map immutable
mutableMap mutable

mapOf() 함수를 사용해서 생성하며 이 때는 type을 명시할 필요 없다.

// to를 써서 짝지어줌
val map = mapOf("apple" to 1, "banana" to 2)

// 값 확인
println(map["apple"])

// 반복문
for((key, value) in map) { ... }

// 전체 확인
map.value
map.key

// contains
map.containsKey("Apple")
map.containsValue(2)

// mutable add
val mutableMap = mutableMapOf<String, Int>()
mutableMap["Apple"] = 1

// remove
mutableMap.remove("Banana")

아이디어

여기서는 쌍이 지어지는 bracket이므로 list/array를 사용하는 것보다 map을 사용하는 게 적합하다.

기타

왜 Generic에 Primitive type은 사용하지 못할까?
https://taler.tistory.com/26

Generic은 compile time에 가 Object로 변하므로 객체가 아닌 Primitive type은 될 수 없다 (그래서 Wrapper type만 됨)

profile
you can do

0개의 댓글