[프로그래머스] 문자열 정렬하기 (1)

Sdoubleu·2023년 4월 1일
0

프로그래머스

목록 보기
15/34
post-thumbnail

문제


내가 쓴 풀이

class Solution {
    fun solution(my_string: String): IntArray {
        val arr = mutableListOf<Int>()
        for(i in my_string)
        if(i.toInt() <= 57) arr.add(i.toString().toInt())
        return arr.sorted().toIntArray()
    }
}

다른 사람 풀이

1) replace함수와 정규식을 이용해서 문자열들을 공백으로 변환
후 남은 정수들을 정렬 후 리스트로 반환

class Solution {
    fun solution(myString: String) 
    = myString.replace("[A-Z|a-z]".toRegex(), "")
        .toList()
        .sorted()
        .map { it.toString().toInt() }
        .toIntArray()
}

-----------------------------------------------------

2) isDigit() 함수로 유효한 정수만 찾고
정수들은 현재 char 타입이므로 map을 이용해서 Int형으로 바꿔서 반환

class Solution {
    fun solution(my_string: String) = my_string.filter{ it.isDigit() }
    .map{ it.toString().toInt() }.sorted()
}
profile
개발자희망자

0개의 댓글