题目:如果两个单词的组成字母完全相同,只是字母的排列顺序不一样,则它们就是变位词,两个单词相同也被认为是变位词。如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>
网友评论