swift - Leetcode Q. 1528. 随机字符串
问题描述
给定一个字符串 s 和一个相同长度的整数数组索引。
字符串 s 将被打乱,使得第 i 个位置的字符移动到打乱字符串中的 indices[i]。
返回打乱的字符串。
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3] 输出:"leetcode"
解释:如图所示,“codeleet”经过洗牌后变成了“leetcode”。
class Solution {
func restoreString(_ s: String, _ indices: [Int]) -> String {
//convert the string into a hash map where all keys are Ints and the values are the Strings.
//Run a for loop through the dictionary and return the key of the value in indices.
//time complexity: O(n)
//Space complexity: O(n)
var newString = s.map{ String($0) }
var y = ""
var count = 0
var dict = [Int:String]()
var z = 0
while count < newString.count {
dict[count] = newString[count]
count += 1
}
while z < indices.count {
y.append(dict[indices[z]]!)
z += 1
}
print(dict)
return y
}
}
第一个 while 循环创建一个字典,第二个 while 循环查找具有匹配键的值并附加到一个字符串中。我的问题是我的代码在错误的位置输出了两个字符。
Input: "codeleet"
[4,5,6,7,0,2,1,3]
Output: "leetcdoe"
你能帮我解释一下我在这里缺少什么吗?
解决方案
它是一对一的散列,而不是您在上面的代码中执行的基于索引的散列,是您的代码的更新正确版本:-
class Solution {
func restoreString(_ s: String, _ indices: [Int]) -> String {
var newString = s.map{ String($0) }
var y = ""
var count = 0
var dict = [Int:String]()
var z = 0
while count < newString.count {
dict[indices[count]] = newString[count]
count += 1
}
while z < indices.count {
y.append(dict[z]!)
z += 1
}
print(dict)
return y
}
}
推荐阅读
- r - 使用 Dplyr 添加比例列
- python - 无法从 Json 或 Yaml 文件或使用 load_model 函数加载模型
- css - 将 Bootstrap 样式应用于 RadioButtonList
- python - 在 PyArray_ResolveWritebackIfCopy() 之前更新 numpy 数组 pre 1.14
- php - 将 JSON 数组传递给 http_build_query
- c++ - 未定义的引用 - 将 2 个字符串调用到一个函数中
- python - 如何在 Python 中消除导致列表错误的项目
- oauth-2.0 - 将数据推送回 Auth0 数据库
- vba - vba 测试列中的单元格,仅以逗号的任何顺序列出单词
- java - Selenium(Java) - 从 csv 或 txt 文件获取 URL 以打开 WebDriver