Keshawn_lu's Blog

Leetcode 1592. 重新排列单词间的空格

字数统计: 554阅读时长: 2 min
2022/09/07 Share

题目简介:

给你一个字符串 text ,该字符串由若干被空格包围的单词组成。每个单词由一个或者多个小写英文字母组成,并且两个单词之间至少存在一个空格。题目测试用例保证text 至少包含一个单词

请你重新排列空格,使每对相邻单词之间的空格数目都 相等 ,并尽可能 最大化 该数目。如果不能重新平均分配所有空格,请 将多余的空格放置在字符串末尾 ,这也意味着返回的字符串应当与原 text 字符串的长度相等。

返回 重新排列空格后的字符串

示例 1:

1
2
3
输入:text = "  this   is  a sentence "
输出:"this is a sentence"
解释:总共有 9 个空格和 4 个单词。可以将 9 个空格平均分配到相邻单词之间,相邻单词间空格数为:9 / (4-1) = 3 个。

示例 2:

1
2
3
输入:text = " practice   makes   perfect"
输出:"practice makes perfect "
解释:总共有 7 个空格和 3 个单词。7 / (3-1) = 3 个空格加上 1 个多余的空格。多余的空格需要放在字符串的末尾。

示例 3:

1
2
输入:text = "a"
输出:"a"

提示:

  • 1 <= text.length <= 100
  • text 由小写英文字母和 ' ' 组成
  • text 中至少包含一个单词

思路:

首先找出每个单词并保存,知道了总空白个数后,每个单词间的空白数便为blank_count / (words.size() - 1)

若有多余空白数,则防止字符串最后即可。

tip:

  • 注意只有一个单词时的特殊处理

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
string reorderSpaces(string text) {

int i = 0;

vector<string> words;

int blank_count = text.size();
while(i < text.size()){

if(text[i] != ' '){

int next_pos = text.find(' ', i);

if(next_pos == -1)
next_pos = text.size();

string word = text.substr(i, next_pos - i);

words.push_back(word);

blank_count -= word.size();

i = next_pos + 1;
}
else
i++;
}

int blank_word;
if(words.size() == 1)
blank_word = blank_count;
else
blank_word = blank_count / (words.size() - 1);

string res;

for(int i = 0; i < words.size(); i++){

res += words[i];

if(i != words.size() - 1){

for(int j = 0; j < blank_word; j++)
res += ' ';

blank_count -= blank_word;
}
}

while(blank_count > 0){

res += ' ';
blank_count--;
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: