代码拉取完成,页面将自动刷新
// Time: O(n)
// Space: O(1)
// inplace solution
class Solution {
public:
string reorderSpaces(string text) {
// count spaces and words
int space_count = 0, word_count = 0;
for (int i = 0; i < size(text); ++i) {
if (text[i] == ' ') {
++space_count;
} else if (i == 0 || text[i - 1] == ' ') {
++word_count;
}
}
// rearrange the spaces to the right
int left = 0, curr = 0;
for (int i = 0; i < size(text); ++i) {
bool has_word = false;
while (i < size(text) && text[i] != ' ') {
swap(text[left++], text[i++]);
has_word = true;
}
if (has_word) {
++left; // keep one space
}
}
// rearrange the spaces to the left
int equal_count = word_count - 1 > 0 ? space_count / (word_count - 1) : 0;
int extra_count = word_count - 1 > 0 ? space_count % (word_count - 1) : space_count;
int right = size(text) - 1 - extra_count;
for (int i = size(text) - 1; i >= 0; --i) {
bool has_word = false;
while (i >= 0 && text[i] != ' ') {
swap(text[right--], text[i--]);
has_word = true;
}
if (has_word) {
right -= equal_count; // keep equal_count spaces
}
}
return text;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。