【问题标题】:Leetcode Q. 1528. Shuffle StringLeetcode Q. 1528. 随机字符串
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢!!这行得通,我没有通过索引进行映射。
【解决方案2】:
class Solution {
public String restoreString(String s, int[] indices) {
    String s1="";
    for(int i=0;i<s.length();i++){
        for(int j=0;j<s.length();j++){
            if(i==indices[j]){
                s1=s1+s.charAt(j);
            }
        }
    }return s1;
}

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2017-05-20
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2023-02-18
    相关资源
    最近更新 更多