포스트

201. 이상한 문자 만들기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func solution(_ s:String) -> String {
    
    var answer : String = ""

    var index = 0
    
    for string in s {
        if string ==  " " {
            index = 0
            answer += " "
        } else if index % 2 == 0 {
            answer += string.uppercased()
            index += 1
        } else {
            answer += string.lowercased()
            index -= 1
        }
    }
    
    print(answer)
    
    return answer
}

enumerated로 하려고했는데 나는 실패했는데 components로 안하고 split으로 한게 문제였던것일까….

결국 인덱스값으로 만들었다….

이것도 처음에 enumerated()를 사용하여 offset,element로 구분하여 offset의 값을 initializing하면서 하고 싶었는데, 의도대로 되지 않았다. 상수이기 때문이었다..

그래서 간략하게 index라는 변수를 만들었고 그 변수를 0 부터 시작하고 1씩 증가하되, “ “을 만나면 제로세팅 하도록 하여 해결하였다.

다른 코드를 보니 거의 근접하게 했던거같은데 뒷심이 부족했던거같다.

다른코드

1
2
3
4
5
import Foundation
func solution(_ s:String) -> String {
    let a = s.components(separatedBy: " ").map { $0.enumerated().map { $0.offset % 2 == 0 ? $0.element.uppercased() : $0.element.lowercased() } }
    return a.map{ $0.map { $0 }.joined() }.joined(separator: " ")
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.