Swift/Code Kata (알고리즘)

[Swift|코드카타] (프로그래머스) #43. 크기가 작은 부분 문자열 - dropFirst(_:), suffix(_:)

yurim-dev 2024. 3. 15. 10:49

🔴 문제

링크: https://school.programmers.co.kr/learn/courses/30/lessons/147355

문제 설명
숫자로 이루어진 문자열 t와 p가 주어질 때, t에서 p와 길이가 같은 부분문자열 중에서, 이 부분문자열이 나타내는 수가 p가 나타내는 수보다 작거나 같은 것이 나오는 횟수를 return하는 함수 solution을 완성하세요.
예를 들어, t="3141592"이고 p="271" 인 경우, t의 길이가 3인 부분 문자열은 314, 141, 415, 159, 592입니다. 이 문자열이 나타내는 수 중 271보다 작거나 같은 수는 141, 159 2개 입니다.

제한사항
1 ≤ p의 길이 ≤ 18p의 길이 ≤ t의 길이 ≤ 10,000t와 p는 숫자로만 이루어진 문자열이며, 0으로 시작하지 않습니다.

입출력 예

 

 

🔵 풀이 1 - Array로 변환

처음 작성했던 코드인데, 코드가 꽤나 무겁다...

어레이로 변형했다가, 다시 스트링, 그리고 정수형으로 변환을 반복해서 그런 것 같다.

import Foundation

func solution(_ t:String, _ p:String) -> Int {
    let arrT: [Character] = Array(t)
    let lenP: Int = p.count
    var count: Int = 0
    for i in 0...(t.count - lenP) {
        if Int(String(arrT[i ..< i + lenP]))! <= Int(p)! {
            count += 1
        }
    }
    return count
}

 

 

🔵 풀이 2 - dropFirst(_:), prefix(_:)

다른 사람의 풀이인데, 가벼워 보이지만 사실은 1번 풀이보다 더 무겁다.

그래도 dropFirst(_:)와 prefix(_:)를 함께 사용한 것이 신선했다.

import Foundation

func solution(_ t:String, _ p:String) -> Int {
    var answer = 0

    for i in 0 ... t.count - p.count {
        let subStr = t.dropFirst(i).prefix(p.count)
        if let comp = Int(subStr), let val = Int(p) {
            answer += comp - val <= 0 ? 1 : 0
        }
    }

    return answer
}

 

▶️ dropFirst(_:)

Complexity

O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop from the beginning of the collection.

 

▶️ prefix(_:)

Complexity

O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.