列表

详情


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

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

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

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

 

示例 1:

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

示例 2:

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

示例 3:

输入:text = "hello   world"
输出:"hello   world"

示例 4:

输入:text = "  walks  udp package   into  bar a"
输出:"walks  udp  package  into  bar  a "

示例 5:

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

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: string reorderSpaces(string text) { } };

golang 解法, 执行用时: 0 ms, 内存消耗: 1.8 MB, 提交时间: 2023-09-27 15:20:03

func reorderSpaces(s string) (ans string) {
    words := strings.Fields(s)
    space := strings.Count(s, " ")
    lw := len(words) - 1
    if lw == 0 {
        return words[0] + strings.Repeat(" ", space)
    }
    return strings.Join(words, strings.Repeat(" ", space/lw)) + strings.Repeat(" ", space%lw)
}

javascript 解法, 执行用时: 60 ms, 内存消耗: 40.8 MB, 提交时间: 2023-09-27 15:19:41

/**
 * @param {string} text
 * @return {string}
 */
var reorderSpaces = function(text) {
    const length = text.length;
    const words = [];
    text.split(' ').forEach(e => {
        if (e.length > 0) {
            words.push(e);
        }
    });
    let cntSpace = length;
    for (const word of words) {
        if (word.length) {
            cntSpace -= word.length;
        }
    }
    let sb = '';
    if (words.length === 1) {
        sb += words[0];
        for (let i = 0; i < cntSpace; i++) {
            sb += ' ';
        }
        return sb;
    }
    const perSpace = Math.floor(cntSpace / (words.length - 1));
    const restSpace = cntSpace % (words.length - 1);
    for (let i = 0; i < words.length; i++) {
        if (i > 0) {
            for (let j = 0; j < perSpace; j++) {
                sb += ' ';
            }
        }
        sb += words[i];
    }
    for (let i = 0; i < restSpace; i++) {
        sb += ' ';
    }
    return sb;
};

cpp 解法, 执行用时: 4 ms, 内存消耗: 6.6 MB, 提交时间: 2023-09-27 15:19:25

class Solution {
public:
    vector<string_view> split(const string_view &str, char trim) {
        int n = str.size();
        vector<string_view> res;
        int pos = 0;
        while (pos < n) {
            while(pos < n && str[pos] == trim) {
                pos++;
            }
            if (pos < n) {
                int curr = pos;
                while(pos < n && str[pos] != trim) {
                    pos++;
                }
                res.emplace_back(str.substr(curr, pos - curr));
            }
        }
        return res;
    }

    string reorderSpaces(string text) {
        int length = text.size();
        vector<string_view> words = split(text, ' ');
        int cntSpace = length;
        int wordCount = 0;
        for (auto &word : words) {
            if (word.size() > 0) {
                cntSpace -= word.size();
                wordCount++;
            }
        }

        string ans;
        if (words.size() == 1) {
            ans.append(words[0]);
            for (int i = 0; i < cntSpace; i++) {
                ans.push_back(' ');
            }
            return ans;
        }
        int perSpace = cntSpace / (wordCount - 1);
        int restSpace = cntSpace % (wordCount - 1);
        for (int i = 0; i < words.size(); i++) {
            if (words[i].size() == 0) {
                continue;
            }
            if (ans.size() > 0) {
                for (int j = 0; j < perSpace; j++) {
                    ans.push_back(' ');
                }
            }
            ans.append(words[i]);
        }
        for (int i = 0; i < restSpace; i++) {
            ans.push_back(' ');
        }
        return ans;
    }
};

java 解法, 执行用时: 3 ms, 内存消耗: 39.8 MB, 提交时间: 2023-09-27 15:19:11

class Solution {
    public String reorderSpaces(String text) {
        int length = text.length();
        String[] words = text.trim().split("\\s+");
        int cntSpace = length;
        for (String word : words) {
            cntSpace -= word.length();
        }
        StringBuilder sb = new StringBuilder();
        if (words.length == 1) {
            sb.append(words[0]);
            for (int i = 0; i < cntSpace; i++) {
                sb.append(' ');
            }
            return sb.toString();
        }
        int perSpace = cntSpace / (words.length - 1);
        int restSpace = cntSpace % (words.length - 1);
        for (int i = 0; i < words.length; i++) {
            if (i > 0) {
                for (int j = 0; j < perSpace; j++) {
                    sb.append(' ');
                }
            }
            sb.append(words[i]);
        }
        for (int i = 0; i < restSpace; i++) {
            sb.append(' ');
        }
        return sb.toString();
    }
}

python3 解法, 执行用时: 28 ms, 内存消耗: 16 MB, 提交时间: 2023-09-27 15:18:52

class Solution:
    def reorderSpaces(self, text: str) -> str:
        words = text.split()
        space = text.count(' ')
        if len(words) == 1:
            return words[0] + ' ' * space
        per_space, rest_space = divmod(space, len(words) - 1)
        return (' ' * per_space).join(words) + ' ' * rest_space

golang 解法, 执行用时: 0 ms, 内存消耗: 2.2 MB, 提交时间: 2021-06-16 17:12:52

func reorderSpaces(text string) string {
    blank := 0
    
    for i := range text {
        if text[i] == ' ' {
            blank++
        }
    }

    re, _ := regexp.Compile("\\s+")
    text = strings.TrimSpace(text)
    text = re.ReplaceAllString(text, " ")
    words := strings.Split(text, " ")

    if len(words) == 1 {
        return text + strings.Repeat(" ", blank)
    }
    
    r := blank % (len(words) - 1)
    ans := strings.Join(words, strings.Repeat(" ", blank/(len(words)-1)))
    if r != 0 {
        ans += strings.Repeat(" ", r)
    }
    return ans

}

上一题