ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์Šคํ‚ฌํŠธ๋ฆฌ(Swift)

2022. 10. 20. 14:09ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์Šคํ‚ฌํŠธ๋ฆฌ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 ๋‚˜์˜ ํ’€์ด

 

์„ ํ–‰๋ฌธ์ œ๋Š” ์ •ํ•ด์ง„ ์ˆœ์„œ์— containsํ•œ์ง€ ํ™•์ธํ•˜๊ณ  first๊ฐ’์ด ์ฒซ๋ฒˆ์งธ ๊ฐ’๊ณผ ๊ฐ™๋‹ค๋ฉด removeFirstํ•˜๊ณ  ์•„๋‹ˆ๋ฉด ์นด์šดํŠธ ์‹œํ‚ค๋ฉด ๋œ๋‹ค.

 

import Foundation

func solution(_ skill:String, _ skill_trees:[String]) -> Int {
    var cnt = skill_trees.count
    
    for tree in skill_trees {
        var skill = Array(skill)
        for t in tree {
            if !skill.contains(t) {
                continue
            } else {
                if skill.first == t {
                    skill.removeFirst()
                } else {
                    cnt -= 1
                    break
                }
            }
        }
    }
      
    return cnt
}

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

hasPrefix๋ฅผ ์ด์šฉํ•ด์„œ ํ‘ผ ์ฝ”๋“œ๊ฐ€ ์ธ์ƒ์ ์ด์—ฌ์„œ ๊ฐ€์ ธ์™”๋‹ค.

"ํฌํ•จ๋œ ๊ฒƒ๋“ค๋งŒ ๋‚จ๊ฒจ์„œ ์ˆœ์„œ๊ฐ€ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค" ๊ฐ€ ํ•ต์‹ฌ์ด๋‹ค.

 

์ถ”๊ฐ€์ ์œผ๋กœ ๋ฐฐ์—ด์„ joinedํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” Stringํƒ€์ž…์ด์—ฌ์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— Mappingํ•˜๊ณ  ์ง„ํ–‰ํ–ˆ๋‹ค.

 

import Foundation

func solution(_ skill:String, _ skill_trees:[String]) -> Int {
    
    let result = skill_trees.filter{ 
        let skills = $0.filter{ skill.contains($0) }.map{String($0)}.joined()
        return skill.hasPrefix(skills)
    }
    return result.count 
}