-
프로그래머스 / 가장 가까운 같은 글자코딩 테스트/Level 1 2022. 12. 8. 19:49반응형
https://school.programmers.co.kr/learn/courses/30/lessons/142086
파이썬
def solution(s): marked = {} answer = [] for index, letter in enumerate(s): answer.append(index - marked[letter] if letter in marked else -1) marked[letter] = index return answer
코틀린
class Solution { fun solution(s: String): IntArray { val answer = mutableListOf<Int>() val counter = mutableMapOf<Char, Int>() for ((index, each) in s.withIndex()) { answer.add(index - (counter[each] ?: (index + 1))) counter[each] = index } return answer.toIntArray() } }
class Solution { fun solution(s: String): IntArray { val counter = mutableMapOf<Char, Int>() return s.withIndex().map { (index, each) -> val temp = counter[each] counter[each] = index if (temp == null) -1 else index - temp }.toIntArray() } }
class Solution { fun solution(s: String) = s.withIndex() .map { (index, each) -> s.slice(0 until index) .lastIndexOf(each) .let { if (it == -1) -1 else index - it } }.toIntArray() }
반응형