持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第22天,点击查看活动详情
一、题目描述:
给你一个字符串 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"
解释:重新排列后,每个字符都还留在原来的位置上。
提示:
- s.length == indices.length == n
- 1 <= n <= 100
- s 仅包含小写英文字母
- 0 <= indices[i] < n
- indices 的所有的值都是 唯一 的
二、思路分析:
从题目描述可得知,若当前字符数组为chs,位于i位置的是字符c,
需要将c挪到indices[i]位置上,但chs[indices[i]]也有对应字符
为了防止字符覆盖,可先处理indices[i]的字符,当indices[i]已处理完毕,则可以将c挪到indices[i]位置上
我们可以通过将处理过的位置设置为-1表示已处理,进行dfs过程即可。
复杂度估计
- 空间复杂度:O(N): 使用字符数组,长度取决于输入字符串。
- 时间复杂度:O(N): 每个字符仅处理一次。
三、AC 代码:
class Solution {
public String restoreString(String s, int[] indices) {
char[] chs = s.toCharArray();
for(int i = 0 ; i < indices.length ; i++) {
if(i == indices[i] || indices[i] == -1) continue;
dfs(chs, indices, i);
}
return String.valueOf(chs);
}
public void dfs(char[] chs, int[] indices, int f) {
if(f >= chs.length || indices[f] == f || indices[f] == -1) return;
char c = chs[f];
int t = indices[f];
indices[f] = -1;
dfs(chs, indices, t);
chs[t] = c;
}
}