1、题目:

输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
2、代码
方式一:
方法一:将String 转换成字符数组chars, 然后创建一个新的字符数组result,长度为字符串的长度,接着以induces数组的值作为新字符串result的索引,值为chars中的元素
package review;
public class Solution1 {
public static String restoreString(String s,int[] indices){
/**
* indices: 4 5 6 7 0 2 1 3
* chars : [c, o, d, e, l, e, e, t]
*/
char[] chars = s.toCharArray();//[c, o, d, e, l, e, e, t]
char[] result = new char[s.length()];
int j = 0;
//indices:4 5 6 7 0 2 1 3
for (int i: indices) {
result[i] = chars[j++];
}
return new String(result);
}
public static void main(String[] args) {
String s = "codeleet";
//System.out.println("char[] chars"+ Arrays.toString(chars));
int[] indices ={4,5,6,7,0,2,1,3};
System.out.println(restoreString(s, indices));
}
}
方式二:
package review;
public class Solution1 {
public static String restoreString(String s,int[] indices){
//方法二:
char[] ans = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
ans[indices[i]] = s.charAt(i);
}
return new String(ans);
}
public static void main(String[] args) {
String s = "codeleet";
//System.out.println("char[] chars"+ Arrays.toString(chars));
int[] indices ={4,5,6,7,0,2,1,3};
System.out.println(restoreString(s, indices));
}
}