250x250
반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자 수니

[LeetCode/Swift] 383. Ransom Note 본문

Algorithm

[LeetCode/Swift] 383. Ransom Note

개발자 수니 2024. 1. 17. 15:10
728x90
반응형

💡 문제 (Easy)

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given two strings 'ransomNote' and 'magazine', return true if 'ransomNote' can be constructed by using the letters from 'magazine' and false otherwise.

Each letter in 'magazine' can only be used once in 'ransomNote'.

두 개의 문자열 ransomNote와 magazine가 주어졌을 때, ransomNote를 magazine의 문자들을 이용하여 만들 수 있으면 True를 반환하고, 그렇지 않으면 False를 반환하는 함수를 작성해야 합니다.

여기서 주의할 점은 magazine의 각 문자는 ransomNote에서 한 번만 사용될 수 있다는 것입니다.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

 

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

 

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

 

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

👩🏻‍💻 해결

1차 firstIndex를 사용하여 글자를 지우는 방법

공간 복잡도 O(n) / 시간 복잡도 O(n)

class Solution {
    func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
        var copy = magazine

        for letter in ransomNote {
            if let index = copy.firstIndex(of: letter) {
                copy.remove(at: index)
            } else {
                return false
            }
        }

        return true
    }
}
728x90
반응형
Comments