首页 > 解决方案 > 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"

你能帮我解释一下我在这里缺少什么吗?

标签: swiftalgorithmdictionaryhashmap

解决方案


它是一对一的散列,而不是您在上面的代码中执行的基于索引的散列,是您的代码的更新正确版本:-

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
    }
}

推荐阅读