[Programmers] [Lv.1] [Swift] 문자열 내 마음대로 정렬하기

doyeonjeong_·2022년 8월 4일
0

프로그래머스

목록 보기
19/35

Hits

문제

문자열 내 마음대로 정렬하기

문제파악하기

  • 배열의 각 요소 중 n번째 문자를 기준으로 정렬
  • 처음엔 이중 배열을 생각했지만 오래걸릴 것 같았다.
  • 그래서 딕셔너리를 사용하고싶었는데 마땅한 아이디어가 떠오르지 않았다.
  • 대충 이런식이었다.
    var dict = [Int:String]()
        for (idx, val) in strings.enumerated() {
            // dictionary를 만들고 
            dict[idx] = val
            let word = strings[i]
            let charIndex = word.index(word.startIndex, offsetBy:n)
            print(word[charIndex])
        }
    print(dict)
  • 근데 아무리 생각해도 잘 모르겠어서 결국 검색했다.

풀이

func solution(_ strings:[String], _ n:Int) -> [String] {
    let result = strings.sorted().map {
        (String(Array($0)[n]), $0)
        // [("c", "abcd"), ("c", "abce"), ("x", "cdx")]
    }.sorted {
        $0.0 < $1.0
        // [("c", "abcd"), ("c", "abce"), ("x", "cdx")]
    }.map {
        $0.1
        // ["abcd", "abce", "cdx"]
    }
    // print(result)
    return result
}

🤔 FEEDBACK

  • sorted().map으로 튜플형식으로 ("n번째 문자", "전체문자")를 만들어준다.
  • 그 다음에 sorted{ $0.0 < $1.0 }을 해주면 튜플의 0번째를 기준으로 오름차순
  • 그 다음 다시 map { $0.1 }을 해주면 1번째 문자만 배열로 반환된다.

다른 풀이

func solution(_ strings:[String], _ n:Int) -> [String] {
    var result:[String] = strings
    for i in 0..<result.count {
        var min:String = result[i]
        var location:Int = i
        for j in i+1..<result.count {
            if min[min.index(min.startIndex, offsetBy: n)] > result[j][result[j].index(result[j].startIndex, offsetBy: n)] || (min[min.index(min.startIndex, offsetBy: n)] == result[j][result[j].index(result[j].startIndex, offsetBy: n)] && min > result[j]) {
                min = result[j]
                location = j
            }
        }
        if i != location {
            swap(&result[i], &result[location])
        }
    }
    return result
}
profile
블로그 이사중 🚚 byukbyak.tistory.com

0개의 댓글