🗒 문제


📝 나의 문제풀이
class Solution {
fun solution(cipher: String, code: Int): String {
return cipher.filterIndexed{idx,_ -> (idx + 1) % code == 0}
}
}
📝 다른 사람의 문제 풀이
다른 사람의 문제 풀이는 좋아요 수가 높거나 많은 사람들이 푼 방법 기준으로 첨부하였습니다.
class Solution {
fun solution(cipher: String, code: Int) = cipher.indices.filter { index -> index % code == code - 1 }.map { cipher[it] }.joinToString("")
}
🖊 문제 풀이 시 알면 좋을 것
filterIndexed — “인덱스 기준 필터링”
fun <T> Iterable<T>.filterIndexed(
predicate: (index: Int, T) -> Boolean
): List<T>
filterIndexed { index, value -> Boolean }
- index : 0부터 시작하는 위치
- value : 해당 위치의 값
- 조건이 true인 요소만 남김
예시
"abcdef".filterIndexed { i, _ -> i % 2 == 0 }
결과: "ace"
indices — 인덱스만 필요할 때
val s = "abc"
println(s.indices)
즉, 0..2 // 0부터 2까지 전부 포함하는 범위
- 0..length-1 범위
- 값 말고 위치만 필요할 때
반응형
'코딩테스트' 카테고리의 다른 글
| [프로그래머스] 숫자 찾기 (0) | 2025.12.21 |
|---|---|
| [프로그래머스] 인덱스 바꾸기 (0) | 2025.12.21 |
| [프로그래머스] 문자열 정렬하기 (1) (0) | 2025.12.21 |
| [프로그래머스] 제곱수 판별하기 (0) | 2025.12.19 |
| [프로그래머스] 문자 반복 출력하기 (0) | 2025.12.19 |