알고리즘/Programmers

[Swift_Programmes] 크기가 작은 부분 문자열

YEN_ 2023. 12. 26. 14:04

 

프로그래머스 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/147355#qna

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


💡 내가 제출한 풀이

import Foundation

func solution(_ t:String, _ p:String) -> Int {
    
    let pCount = p.count, tCount = t.count
    let pNum = Int(p)!
    var result = 0
    
    for i in 0 ... tCount - pCount {
        let item = t.dropFirst(i).prefix(pCount)
        if pNum >= Int(item)! { 
            result += 1
        }
    }
    
    return result
}

💡 풀이 과정

 

p의 count씩 t를 순서대로 쪼개서 나온 숫자가 만약 p보다 작거나 같은 숫자의 갯수를 반환하는 문제이다

 

 

우선 필요한 요소들을 변수,상수에 담아서 미리 계산해둔다

let pCount = p.count, tCount = t.count  // 각 매개변수의 count
let pNum = Int(p)!  // 주어진 P를 Int형으로 형변환
var result = 0      // return 할 값을 담을 변수

 

t를 pCount씩 쪼갤 수 있는 횟수는 tCount에서 pCount만큼을 뺏 숫자만큼이다

for i in 0 ... tCount - pCount

 

✔️ dropFirst(_:)

dropFirst(_:)는 주어진 숫자 만큼의 초반 인덱스를 제외한 나머지를 반환해주는메소드이다.

let arr = "123456789"

arr.dropFirst(2)
// 3456789

위의 예시와 같이 숫자가 주어지면 해당하는 숫자만큼을 앞에서 drop하는 메소드이다.

 

✔️ prefix(_:)

문자열의 앞부분부터 주어진 숫자의 갯수를 잘라주는 메소드이다

 

 

 

제출 코드의 경우, 반복문을 돌려서 새로운 연산이 시작될 때 마다 dropFirst로 앞에서부터 1개씩 버려주도록 했다

첫번째는 아무것도 버리면 안되므로 0부터 시작하여 맨 처음에 연산되는 것은 온전한 형태이다

 

그 다음 prefix를 사용해서 pCount의 갯수만큼 t를 잘라서 item에 담는다

for i in 0 ... tCount - pCount {
    let item = t.dropFirst(i).prefix(pCount)
    if pNum >= Int(item)! { 
        result += 1
    }
}

 

t = "3141592", p = "271" 가 주어졌을 때

첫번째 연산에서 item은 314

두번째 연산에서 item은 141

... 이런 순서로 선택된다

 

 

 

 

 

https://developer.apple.com/documentation/swift/string/dropfirst(_:)

 

dropFirst(_:) | Apple Developer Documentation

Returns a subsequence containing all but the given number of initial elements.

developer.apple.com

 

https://developer.apple.com/documentation/swift/array/prefix(_:)

 

prefix(_:) | Apple Developer Documentation

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

developer.apple.com