본문 바로가기

Study/알고리즘

[프로그래머스] 12903. 가운데 글자 가져오기 (swift)

 

 

코딩테스트 연습 - 가운데 글자 가져오기

단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다. 재한사항 s는 길이가 1 이상, 100이하인 스트링입니다. 입출력 예 s ret

programmers.co.kr

 

문제 설명

1. 문자열 s의 가운데 글자를 반환하는 함수 구현하기.

2. 단어의 길이가 짝수라면 가운데 두 글자를 반환.

 

 

풀이

1. 홀수일 때와 짝수일 때의 경우를 나누어 return 

 

import Foundation

func solution(_ s: String) -> String {
    let len: Int = s.count
    let index = s.index(s.startIndex, offsetBy: len/2)
    if len % 2 == 1 {
        return String(s[index...index])
    } else {
        let startIndex = s.index(s.startIndex, offsetBy: len/2-1)
        return String(s[startIndex...index])
    }
}

 

 

 

코드 개선

1. 어차피 subString을 이용할 것이라면, 경우를 나눌 필요가 없다.

 

import Foundation

func solution(_ s: String) -> String {
    let len: Int = s.count
    let startIndex = s.index(s.startIndex, offsetBy: (len-1)/2)
    let endIndex = s.index(s.startIndex, offsetBy: len/2)
    return String(s[startIndex...endIndex])
}

 


 

String.Index 타입 공부하기!