You are given a string text
of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It’s guaranteed that text
contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text
.
Return the string after rearranging the spaces.
Example 1:
Input: text = " this is a sentence " Output: "this is a sentence" Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.
Example 2:
Input: text = " practice makes perfect" Output: "practice makes perfect " Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.
Example 3:
Input: text = "hello world" Output: "hello world"
Example 4:
Input: text = " walks udp package into bar a" Output: "walks udp package into bar a "
Example 5:
Input: text = "a" Output: "a"
Constraints:
1 <= text.length <= 100
text
consists of lowercase English letters and' '
.text
contains at least one word.
Solution: Simulation
Time complexity: O(n)
Space complexity: O(n) -> O(1)
C++
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 |
// Author: Huahua class Solution { public: string reorderSpaces(string text) { vector<string> words; string word; int t = 0; for (char c : text) { if (c == ' ') { ++t; if (!word.empty()) { words.push_back(word); word.clear(); } } else { word += c; } } if (!word.empty()) words.push_back(word); const int n = words.size(); if (n == 1) return words[0] + string(t, ' '); const int s = t / (n - 1); const int r = t % (n - 1); string ans; for (int i = 0; i < words.size(); ++i) { if (i) ans.append(s, ' '); ans += words[i]; } ans.append(r, ' '); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment