From a429f598af4f036871ace8bb600967cc155f9533 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Thu, 20 Jun 2024 08:12:22 +0100 Subject: [PATCH] feat: add swift implementation to lcof2 problem: No.064 --- .../README.md" | 56 +++++++++++++++++++ .../Solution.swift" | 50 +++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/Solution.swift" diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" index 29c7473d49328..14e5e92a1f808 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" @@ -257,6 +257,62 @@ func patterns(word string) []string { */ ``` +#### Swift + +```swift +class MagicDictionary { + private var words: Set + private var counter: [String: Int] + + init() { + words = Set() + counter = [String: Int]() + } + + func buildDict(_ dictionary: [String]) { + for word in dictionary { + words.insert(word) + for pattern in patterns(word) { + counter[pattern, default: 0] += 1 + } + } + } + + func search(_ searchWord: String) -> Bool { + for pattern in patterns(searchWord) { + let count = counter[pattern, default: 0] + if count > 1 || (count == 1 && !words.contains(searchWord)) { + return true + } + } + return false + } + + private func patterns(_ word: String) -> [String] { + var result = [String]() + var chars = Array(word) + for i in 0.. diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/Solution.swift" new file mode 100644 index 0000000000000..f4044e87d82fc --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/Solution.swift" @@ -0,0 +1,50 @@ +class MagicDictionary { + private var words: Set + private var counter: [String: Int] + + init() { + words = Set() + counter = [String: Int]() + } + + func buildDict(_ dictionary: [String]) { + for word in dictionary { + words.insert(word) + for pattern in patterns(word) { + counter[pattern, default: 0] += 1 + } + } + } + + func search(_ searchWord: String) -> Bool { + for pattern in patterns(searchWord) { + let count = counter[pattern, default: 0] + if count > 1 || (count == 1 && !words.contains(searchWord)) { + return true + } + } + return false + } + + private func patterns(_ word: String) -> [String] { + var result = [String]() + var chars = Array(word) + for i in 0..