【发布时间】:2022-09-23 14:03:33
【问题描述】:
我正在解决 leetcode 问题 249. Group Shifted Strings。有人可以解释一下密钥是如何存储在 hashMap 中的吗?
We can shift a string by shifting each of its letters to its successive letter.
For example, \"abc\" can be shifted to be \"bcd\".
We can keep shifting the string to form a sequence.
For example, we can keep shifting \"abc\" to form the sequence: \"abc\" -> \"bcd\" -> ... -> \"xyz\".
Given an array of strings strings, group all strings[i] that belong to the same shifting sequence. You may return the answer in any order.
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\"]]\"
-
你在寻找 LeetCode 问题的解释吗?如果是这样,那么 SO 与 LeetCode 有什么关系?还是问题是别的?