从Leetcode 每日一题练习继续讨论:
2109. 向字符串添加空格
2109. Adding Spaces to a String
题解
本题按照题意在对应的位置插入空格并构造新字符串,可以创建一个空的新字符串,在扫描原字符串的同时在给定的下标位置插入空格,再继续遍历原字符串,用一个变量记录原字符串遍历到的下标。当遍历到的下标满足要插入空格的位置时在新字符串中插入一个空格,继续遍历并复制原始字符串。
代码
class Solution {
public:
string addSpaces(string s, vector<int>& spaces) {
string news = "";
int index = 0;
int n = s.size();
for(const int& space : spaces){
while(index != space){
news.push_back(s[index]);
index++;
}
news.push_back(' ');
}
news.append(s,index,n);
return news;
}
};