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..