[LeetCode] Adding Spaces to a String

2109. Adding Spaces to a String

You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.

  • For example, given s = “EnjoyYourCoffee” and spaces = [5, 9], we place spaces before ‘Y’ and ‘C’, which are at indices 5 and 9 respectively. Thus, we obtain “Enjoy Your Coffee”.

Return the modified string after the spaces have been added.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string addSpaces(string s, vector<int>& spaces) {
string res = "";
for(int i = s.length() - 1; i >= 0; i--) {
res.push_back(s[i]);
if(!spaces.empty() and spaces.back() == i) {
res.push_back(' ');
spaces.pop_back();
}
}
reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/24/PS/LeetCode/adding-spaces-to-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.