我正在解决leetcode问题249.分组移位字符串.有人能解释一下密钥是如何存储在hashMap中的吗?
我们可以通过将字符串的每个字母移到其连续的字母来移位字符串.
例如,"abc"可以改为"bcd". 我们可以不断地移动弦以形成一个序列. 例如,我们可以不断移动"abc"以形成序列:"abc"->;"bcd"->;...->;"xyz".
给出一个字符串数组,将属于同一移位序列的所有strings[i]
个字符串分组成一组.你可以按任何顺序交回答案.
Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"]
Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]
func groupStrings(_ strings: [String]) -> [[String]] {
var dict = [[Int]: [String]]()
for word in strings {
var key = [0]
if word.count > 1 {
var a = Array(word)
let pivot = Int(a[0].asciiValue!) - 97
for i in 1..<a.count {
let index = (Int(a[i].asciiValue!) - 97 + 26 - pivot) % 26
key.append(index)
}
}
if var array = dict[key] {
array.append(word)
dict[key] = array
} else {
dict[key] = [word]
}
}
return dict.keys.compactMap { dict[$0] }
}
"[[0, 2, 4, 5]: ["acef"], [0, 25]: ["az", "ba"], [0]: ["a", "z"], [0, 1, 2]: ["abc", "bcd", "xyz"]]"