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.

这题提取出所有的词,然后计算空格数即可。


class RearrangeSpacesBetweenWords : public Solution {
public:
    void Exec() {
        
    }
    string reorderSpaces(string text) {
        string str;
        vector<string> strs;
        int blankCount = 0;
        for (int i = 0; i < text.size(); i++) {
            if (text[i] == ' ') {
                blankCount++;
                if (!str.empty()) {
                    strs.push_back(std::move(str));
                }
            } else {
                str.push_back(text[i]);
            }

            if (i == text.size() - 1) {
                if (!str.empty()) {
                    strs.push_back(std::move(str));
                }
            }
        }
        int blankAvg = 0;
        if (strs.size() > 1) {
            blankAvg = blankCount / (strs.size() - 1);
        }

        for (auto &v : strs) {
            str += v;
            for (int i = 0; i < blankAvg && blankCount > 0; i++) {
                str.push_back(' ');
                blankCount--;
            }
        }
        for (int i = 0; i < blankCount; i++) {
            str.push_back(' ');
        }
        return str;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day