관리 메뉴

나만을 위한 블로그

[Algorithm] 프로그래머스 - 인덱스 바꾸기 (Kotlin) 본문

알고리즘 문제 풀이/프로그래머스

[Algorithm] 프로그래머스 - 인덱스 바꾸기 (Kotlin)

참깨빵위에참깨빵_ 2023. 1. 8. 20:35
728x90
반응형
문자열과 정수 num1, num2가 매개변수로 주어질 때, 문자열에서 인덱스 num1과 num2에 해당하는 문자를 바꾼 문자열을 리턴하는 solution()을 완성하라

 

 

먼저 주먹구구식으로 풀어봤다. 임시 변수를 만들고 두 인덱스의 값을 서로 바꾼 다음 문자열로 만들어 리턴하는 코드인데 통과 처리됐다.

 

class Solution {
    fun solution(str: String, num1: Int, num2: Int): String {
        val list = str.toCharArray()
        val temp = list[num1]
        list[num1] = list[num2]
        list[num2] = temp

        return list.joinToString("")
    }
}

 

이걸 어떻게 줄일 수 있을까 고민해봤는데 딱히 좋은 방법이 떠오르지 않아서 다른 사람의 풀이를 참고했다.

 

import java.util.*

class Solution {
    fun solution(myString: String, num1: Int, num2: Int): String {
        return myString.toList().let {
            Collections.swap(it, num1, num2)
            it.joinToString("")
        }
    }
}

 

Collections의 함수 중 하나인 swap()을 쓰고 문자열로 만들어 리턴하는 코드다. 이름만 보면 뭘 하는 함수인지 유추는 되지만 정확히 어떤 함수인지 몰라서 공식문서를 확인했다.

 

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap(java.util.List,%20int,%20int) 

 

Collections (Java Platform SE 7 )

Rotates the elements in the specified list by the specified distance. After calling this method, the element at index i will be the element previously at index (i - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. (Thi

docs.oracle.com

지정된 리스트의 지정된 위치에 있는 요소를 교체한다. 지정된 위치가 동일하면 이 메서드를 호출해도 리스트가 바뀌지 않는다

< 메서드 매개변수 >

list : 요소를 교환할 리스트
i : 교체할 한 요소의 인덱스
j : 교체할 다른 요소의 인덱스
public static void swap(List<?> list, int i, int j) {
    // instead of using a raw type here, it's possible to capture
    // the wildcard but it will require a call to a supplementary
    // private method
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}

 

Collections에 속하는 static 메서드기 때문에 맨 위에 import문을 써 줘야 한다. let {}이 뭘 하는지 모른다면 코틀린의 범위 지정함수를 확인해보면 될 것이다.

반응형
Comments