Skip to content

[Algorithm] 가운데 글자 가져오기 #7

Closed
@hwangJi-dev

Description

@hwangJi-dev

📌 TODO

  • 문제 풀이
  • 정리

가운데 글자 가져오기

💬 Idea

  • 홀수 / 짝수를 구분
    • 짝수일 경우에는 문자열의 중앙에 위치한 2개의 문자를 추출하기 위해 s.count / 2 위치부터 s.count / 2 + 1 위치까지의 문자를 추출한다.
    • 홀수일 경우에는 문자열의 중앙에 위차한 1개의 문자를 추출하기 위해 s.count / 2 위치의 문자 하나를 추출한다.

💬 풀이

func solution(_ s:String) -> String {

    if s.count % 2 == 0 {
        let index = s.index(s.startIndex, offsetBy: s.count / 2 - 1)..<s.index(s.startIndex, offsetBy: s.count / 2 + 1)
        return String(describing: s[index])
    } else {
        let index = s.index(s.startIndex, offsetBy: s.count / 2)
        return String(describing: s[index])
    }
}

소요시간 : 20분 4초


💬 더 나은 방법?

  • String.Index를 사용하여 간단하게 String을 반환하기
  • 홀수, 짝수의 경우를 구분하지 않고 수식으로 해결하기
func solution(_ s:String) -> String {

    return String(s[String.Index(utf16Offset: (s.count - 1) / 2, in: s)...String.Index(utf16Offset: s.count / 2, in: s)])
}

💬 알게된 문법

✅ String.Index

  • 문자열에서 문자 또는 코드 단위의 위치
    • 지정된 UTF-16 코드 단위 오프셋에서 새 인덱스를 만든다.

    • Swift 문자열에서는 string[0]과 같이 index를 통한 접근이 불가능하다.

      'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
      
      //**'subscript(_:)'를 사용할 수 없습니다. String을 Int로 첨자할 수 없습니다. 대신 String.Index를 사용하세요.**
    • 따라서 String.Index를 사용하여 문자열의 인덱스에 접근할 수 있다.

  • init(utf16Offset:in:)
    • index를 복잡하게 구하지 않고 정수(Int)를 이용하여 쉽게 구할 수 있는 이니셜라이저

      String(s[String.Index(utf16Offset: (s.count - 1) / 2, in: s)...String.Index(utf16Offset: s.count / 2, in: s)])

✅ Array(s)

  • Array를 사용하여 문자열을 배열로 변환합니다.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions