개인공부/알고리즘

프로그래머스 - 잘라서 배열로 저장하기 (Kotlin)

KEEMSY 2023. 7. 24. 11:46

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

이 문제 해결의 핵심은, 원하는 길이만큼 문자열의 길이를 추출할 수 있는가? 이다.

  • 문자열을 자르는 방법에는 String.chunked(size:Int): List<String>(개수를 기준으로 문자열 자르기) 와 String.substring() 를 이야기 할 수 있다.
  • 해당 문제에서 나는 substring을 사용하는 방식으로 풀이를하고, chunked 방법을 알게되었다.
class Solution {
    fun solution(my_str: String, n: Int): Array<String> {
        val answer = mutableListOf<String>()

        var start = 0
        while (start < my_str.length) {
            if (my_str.length >= start + n) {
                answer.add(my_str.substring(start, start + n))            
            }
            else {
                answer.add(my_str.substring(start))
            }
            start += n
        }
        return answer.toTypedArray()
    }
}
class Solution {
    fun solution(my_str: String, n: Int): Array<String> = my_str.chunked(n).toTypedArray()
}

 

728x90