[kotlin]튜플

Heejin Ryu·2021년 7월 27일
0

fun solution(s: String): IntArray {
        var hashMap = hashMapOf<Long, Int>()
        var options = arrayListOf<Int>()
        s.substring(1, s.length-1)
            .split(',')
            .toList()
            .forEach {
                var tmp = it
                if ("{" in tmp) {
                    tmp = tmp.substring(1, tmp.length)
                }
                if ("}" in tmp) {
                    tmp = tmp.substring(0, tmp.length-1)
                }
                options.add(tmp.toInt())
            }
        for (option in options) {
            hashMap.put(option.toLong(), hashMap.getOrDefault(option.toLong(), 0)+1)
        }
        var sortedMap = hashMap.toList().sortedWith(compareBy({it.second})).toMap().keys.reversed()
        return  sortedMap.map { it.toString().toInt() }.toIntArray()

    }
  1. 체이닝을 계속 걸고 싶었는데, split에서 regex를 '},{로 하려고 하니, 너무 짧다는 오류가 나왔다. 그래서 forEach문을 통해서 한 번 더 걸러주었는데 이 부분이 조금 길어졌다. 이는 string으로 "},{" 이렇게 split을 하면 가능하다.
  2. split을 한 뒤, Unit의 형식이 나왔는데 이는 asSequence를 체이닝 걸어주면 되는 듯 하다.
  3. hashMap을 통해서 키와 밸류를 설정하고, 밸류로 sort를 한 다음 reverse해주었다.
profile
Chocolate lover🍫 & Junior Android developer🤖

0개의 댓글