【发布时间】:2021-08-07 07:53:05
【问题描述】:
给定一个字符串 s 和一个相同长度的整数数组索引。
字符串 s 将被打乱,使得第 i 个位置的字符移动到打乱字符串中的 indices[i]。
返回洗牌后的字符串。
输入:s = "codeleet",索引 = [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"
你能帮我解释一下我在这里缺少什么吗?
【问题讨论】:
-
改组(a)字符串是什么意思?
-
我认为你误解了这个任务。字符 a 位置 i 应放入位置 indices[i]。你正在做相反的事情。我建议再看看leetcode.com/problems/shuffle-string中的图表。
-
你返回 y 但打印 dict。对吗?
-
这很简单。只需将字符串拆分为数组字符,然后将该数组字符插入带有索引的新数组。
-
如果它可以工作并且您也理解,请在下面的答案中标记为已接受,谢谢
标签: swift algorithm dictionary hashmap