본문 바로가기
Problem Solving

[Swift] 프로그래머스 옹알이(1) (lv.0)

by DuncanKim 2023. 1. 12.
728x90

[Swift] 프로그래머스 옹알이(1) (lv.0)

 

1. 문제

https://school.programmers.co.kr/learn/courses/30/lessons/120956

 

 

0렙에서 가장 정답률이 낮은 문제이다. 문자열 처리를 요구하는데, Swift에 있는 replacingOccurrences() 함수를 활용하면 그렇게 어렵지 않게 풀 수 있다.

 

2. 접근

어떤 문자열이 주어지든 간에 말할 수 있는 발음은 네 가지 밖에 없고, 각 문자열에서 최대 한 번씩만 등장하기 때문에 replacingOccurrences(of:with:)를 활용하면 된다.

 

https://developer.apple.com/documentation/foundation/nsstring/1412937-replacingoccurrences

 

Apple Developer Documentation

 

developer.apple.com

 

이 함수를 사용해서 각 발음에 해당하는 문자를 먼저 공백으로 치환해서 count == 0 이면 답을 하나씩 증가시키려고 했는데, 생각해보니, yayae의 경우, aya가 먼저 치환되면 ye가 남아 말할 수 있는 발음으로 인식한다는 것을 풀다가 알았다.

그래서 "1"로 치환을 시키고, 남겨진 문자를 숫자로 변경할 수 있다면 답을 하나씩 증가시키겠다는 생각을 하였다.

 

코드는 아래와 같이 작성하였다.

 

3. 코드

import Foundation

func solution(_ babbling:[String]) -> Int {
    let pronunciation = ["aya", "ye", "woo", "ma"]
    var answer = 0
    var tempBabbling = babbling
    
    for i in 0 ... tempBabbling.count - 1 {
        for k in pronunciation {
            tempBabbling[i] = tempBabbling[i].replacingOccurrences(of: k, with: "1")
        }
        if Int(tempBabbling[i]) != nil {
            answer += 1
        }
    }
    return answer
}
728x90

댓글