swift Swift中anagram算法的例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift中anagram算法的例子相关的知识,希望对你有一定的参考价值。

//Anagram - Two words that contain the same characters

let testWord = "abcde"
let testWord2 = "edcba"

func isAnagram(word word: String, isAnagramOf word2: String) -> Bool {
    guard
        let word1Dictionary = countChars(word),
        let word2Dictionary = countChars(word2) else {
            return false
    }
    
    for (k, v) in word1Dictionary {
        guard v == word2Dictionary[k] else {
            return false
        }
    }
    return true
}

func countChars(word: String?) -> [Character: Int]? {
    guard let word = word where word != "" else {
        return nil
    }
    var dictionary = [Character: Int]()
    
    for char in word.characters {
        if let currentValue = dictionary[char] {
            dictionary.updateValue(currentValue + 1, forKey: char)
        } else {
            dictionary[char] = 1
        }
    }
    return dictionary
}

isAnagram(word: testWord1, isAnagramOf: testWord2)

以上是关于swift Swift中anagram算法的例子的主要内容,如果未能解决你的问题,请参考以下文章

Swift Anagram 检查器

如何使用 EZAudio 在 Swift 中获取 FFT 数据?

Swift4.2循环引用的例子讲解

swift中的DES加密解密算法

Swift的排序算法总结

swift 用户等同的例子