알고리즘 - 문자열 정렬하기 (2) - 120911

워니·2023년 4월 2일

알고리즘

목록 보기
12/30
post-thumbnail

[level 0] 문자열 정렬하기 (2) - 120911

문제 링크

성능 요약

메모리: 83 MB, 시간: 3.80 ms

구분

코딩테스트 연습 > 코딩테스트 입문

채점결과


정확성: 100.0
합계: 100.0 / 100.0

문제 설명

영어 대소문자로 이루어진 문자열 my_string이 매개변수로 주어질 때, my_string을 모두 소문자로 바꾸고 알파벳 순서대로 정렬한 문자열을 return 하도록 solution 함수를 완성해보세요.


제한사항
  • 0 < my_string 길이 < 100

입출력 예
my_string result
"Bcad" "abcd"
"heLLo" "ehllo"
"Python" "hnopty"

입출력 예 설명

입출력 예 #1

  • "Bcad"를 모두 소문자로 바꾸면 "bcad"이고 이를 알파벳 순으로 정렬하면 "abcd"입니다.

입출력 예 #2

  • "heLLo"를 모두 소문자로 바꾸면 "hello"이고 이를 알파벳 순으로 정렬하면 "ehllo"입니다.

입출력 예 #3

  • "Python"를 모두 소문자로 바꾸면 "python"이고 이를 알파벳 순으로 정렬하면 "hnopty"입니다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges


  • 내 풀이
class Solution {
    public String solution(String my_string) {
        String[] arr = my_string.toLowerCase().split("");

        return Arrays.asList(arr).stream().sorted().collect(Collectors.joining());
    }

}
  • TDD
class SolutionTest {

    @Test
    @DisplayName("Bcad = abcd")
    void solution() {
        Assertions.assertThat(new Solution().solution("Bcad")).isEqualTo("abcd");
    }

    @Test
    @DisplayName("heLLo = ehllo")
    void solution2() {
        Assertions.assertThat(new Solution().solution("heLLo")).isEqualTo("ehllo");
    }

    @Test
    @DisplayName("Python = hnopty")
    void solution3() {
        Assertions.assertThat(new Solution().solution("Python")).isEqualTo("hnopty");
    }
}

  • 풀이
    stream을 사용하여 간결하게 구현하고자 고민했다.
    아직 stream에 대해서 명확하게 이해가 되지않는것같다.
    인자값으로 들어온 my_string을 string[]에 split으로 쪼꺠고 소문자로 변환후 집어넣는다
    string[]을 arrays.asList를 통해 arrayList형태로 변환후
    stream을 이용해 정렬, joining을 이용해
    list안에 값들을 붙여준 후 return 해줬다.
profile
Backend-Dev

0개의 댓글