给你一个下标从 0 开始的字符串 s
,以及一个下标从 0 开始的整数数组 spaces
。
数组 spaces
描述原字符串中需要添加空格的下标。每个空格都应该插入到给定索引处的字符值 之前 。
- 例如,
s = "EnjoyYourCoffee"
且spaces = [5, 9]
,那么我们需要在'Y'
和'C'
之前添加空格,这两个字符分别位于下标5
和下标9
。因此,最终得到"Enjoy Your Coffee"
。
请你添加空格,并返回修改后的字符串。
class Solution {
public String addSpaces(String s, int[] spaces) {
StringBuilder ans=new StringBuilder(s.length()+spaces.length);
int j=0;
for(int i=0;i<s.length();i++)
{
if(j<spaces.length&&spaces[j]==i)
{
ans.append(' ');
j++;
}
ans.append(s.charAt(i));
}
return ans.toString();
}
}
如果输入s="nicetomeetyou".spaces[4,6,10]
- 当
i = 0
时,j = 0
,spaces[0] = 4
,不满足spaces[j] == i
,执行ans.append(s.charAt(0))
,此时ans
为"n"
。 - 当
i = 1
时,同理,执行ans.append(s.charAt(1))
,ans
变为"ni"
。 - 当
i = 2
时,执行ans.append(s.charAt(2))
,ans
变为"nic"
。 - 当
i = 3
时,执行ans.append(s.charAt(3))
,ans
变为"nice"
。 - 当
i = 4
时,j = 0
,spaces[0] = 4
,满足j < spaces.length && spaces[j] == i
,先执行ans.append(' ')
,此时ans
为"nice "
,然后j++
,j
变为1
,再执行ans.append(s.charAt(4))
,ans
变为"nice t"
。 - 当
i = 5
时,不满足spaces[j] == i
(此时spaces[1] = 6
),执行ans.append(s.charAt(5))
,ans
变为"nice to"
。 - 当
i = 6
时,满足j < spaces.length && spaces[j] == i
(此时j = 1
,spaces[1] = 6
),先执行ans.append(' ')
,ans
变为"nice to "
,然后j++
,j
变为2
,再执行ans.append(s.charAt(6))
,ans
变为"nice to m"
。 - 后续以此类推,继续遍历字符串
s
,当i = 10
时,满足条件,添加空格。