美文网首页iOS猿媛圈
Swift-变位词判断

Swift-变位词判断

作者: FlyElephant | 来源:发表于2016-12-27 09:58 被阅读7次

    题目:如果两个单词的组成字母完全相同,只是字母的排列顺序不一样,则它们就是变位词,两个单词相同也被认为是变位词。如tea 与eat , nic 与cin, ddc与dcd, abc与abc.
    核心代码:
    <pre><code>`
    func isAnagram(first:String,next:String) -> Bool {
    if first == next {
    return true
    }

        var dict:[String:Int] = [:]
        for i in 0..<first.characters.count {
            let char:String = first[i]
            if dict[char] != nil {
                let count:Int = dict[char]!
                dict[char] = count + 1
            } else {
               dict[char] = 1
            }
        }
        
        for i in 0..<next.characters.count {
            let char:String = next[i]
            if dict[char] != nil {
                let count:Int = dict[char]!
                dict[char] = count - 1
            }
        }
        
        var result:Bool = true
        for (_,value) in dict {
            if value != 0 {
                result = false
            }
        }
        return result
    }`</code></pre>
    

    测试代码:
    <pre><code>`

    var isAnagram:Bool = hashSearch.isAnagram(first: "abca", next: "baccccc")
    print("FlyElephant-是否是变位词---(isAnagram)")`</code></pre>

    相关文章

      网友评论

        本文标题:Swift-变位词判断

        本文链接:https://www.haomeiwen.com/subject/hdbsvttx.html