【问题标题】:What's the problem and How can I resolve it in this code?有什么问题,我该如何在这段代码中解决它?
【发布时间】:2021-07-06 04:38:00
【问题描述】:

问题-

给定一个字符串 s 和一个相同长度的整数数组索引。 字符串 s 将被打乱,使得第 i 个位置的字符移动到打乱字符串中的 indices[i]。 返回打乱的字符串

输入:s = "aiohn",索引 = [3,1,4,2,0] , 正确输出:“nihao” ,我的输出:“hinoa”

输入:s = "aaiougrt",索引 = [4,0,2,6,7,3,1,5] , 正确输出:“arigatou” ,我的输出:“uairtoag”

class Solution {
    public String restoreString(String s, int[] indices) {
        
        String res= "";
        
        for(int i=0 ; i<s.length() ; i++){
            res+= s.charAt(indices[i]);
        }
        
        return res;
    }
}

【问题讨论】:

    标签: java arrays string


    【解决方案1】:

    你可以这样做:

    class Solution {
        public String restoreString(String s, int[] indices) {
            char[] chars = new char[s.length()];
            
            for(int i = 0 ; i < s.length() ; i++){
                chars[indices[i]] = s.charAt(i);
            }
            
            return new String(chars);
        }
    }
    

    你所做的恰恰相反,res中的第i个字符是str.charAt(indices[i]);

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2022-06-10
      • 2015-06-13
      • 2015-04-25
      相关资源
      最近更新 更多