1. 程式人生 > 其它 >1528. 重新排列字串

1528. 重新排列字串

技術標籤:leetcode字串leetcodehashmap

1528. 重新排列字串

  1. 重新排列字串
    給你一個字串 s 和一個 長度相同 的整數陣列 indices 。

請你重新排列字串 s ,其中第 i 個字元需要移動到 indices[i] 指示的位置。

返回重新排列後的字串。

示例 1:

輸入:s = “codeleet”, indices = [4,5,6,7,0,2,1,3]
輸出:“leetcode”
解釋:如圖所示,“codeleet” 重新排列後變為 “leetcode” 。
示例 2:

輸入:s = “abc”, indices = [0,1,2]
輸出:“abc”
解釋:重新排列後,每個字元都還留在原來的位置上。

示例 3:

輸入:s = “aiohn”, indices = [3,1,4,2,0]
輸出:“nihao”
示例 4:

輸入:s = “aaiougrt”, indices = [4,0,2,6,7,3,1,5]
輸出:“arigatou”

思路:考察hashmap :
先用一個hashmap對映字元和數字,把陣列重新排序一下,
列印Hashmap

package 期末;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;

/*
 * 1528. 重新排列字串
給你一個字串 s 和一個 長度相同 的整數陣列 indices 。

請你重新排列字串 s ,其中第 i 個字元需要移動到 indices[i] 指示的位置。

返回重新排列後的字串。

 

示例 1:



輸入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
輸出:"leetcode"
解釋:如圖所示,"codeleet" 重新排列後變為 "leetcode" 。
示例 2:

輸入:s = "abc", indices = [0,1,2]
輸出:"abc"
解釋:重新排列後,每個字元都還留在原來的位置上。
示例 3:

輸入:s = "aiohn", indices = [3,1,4,2,0]
輸出:"nihao"
示例 4:

輸入:s = "aaiougrt", indices = [4,0,2,6,7,3,1,5]
輸出:"arigatou"

思路:考察hashmap :
先用一個hashmap對映字元和數字,把陣列重新排序一下,
列印Hashmap
 */
public class a1528重新排列字串 { public static String restoreString(String s, int[] indices) { HashMap<Integer, Character> ha =new HashMap<Integer, Character>(); char []ch =s.toCharArray(); int index=0; for (char c : ch) { ha.put(indices[index], c);// index++; } Arrays.
sort(indices); //陣列重新排序 StringBuilder res =new StringBuilder(); for (int i = 0; i < indices.length; i++) { res.append(ha.get(indices[i])); } // System.out.println(res.toString()); return res.toString(); } public static void main(String[] args) { // restoreString("codeleet",new int[]{4,5,6,7,0,2,1,3}); restoreString("aiohn",new int[]{3,1,4,2,0}); } }

官方答案

class Solution {
    public String restoreString(String s, int[] indices) {
        int length = s.length();
        char[] result = new char[length];

        for (int i = 0; i < length; i++) {
            result[indices[i]] = s.charAt(i);
        }
        return new String(result);
    }
}

來源:力扣leetcode