亲宝软件园·资讯

展开

Java C++ 单词间空格重排

AnjaVon 人气:0

题目要求

思路:模拟

Java

class Solution {
    public String reorderSpaces(String text) {
        int n = text.length(), spcnt = 0;
        List<String> words = new ArrayList<>();
        for (int i = 0; i < n; ) {
            if (text.charAt(i) == ' ' && ++i >= 0 && ++spcnt >= 0)
                continue;
            int j = i;
            while (j < n && text.charAt(j) != ' ')
                j++;
            words.add(text.substring(i, j)); // 单词
            i = j;
        }
        StringBuilder res = new StringBuilder();
        int m = words.size(), dis = spcnt / Math.max(m - 1, 1);
        String spcs = ""; // 两单词间的空格
        while (dis-- > 0)
            spcs += " ";
        for (int i = 0; i < m; i++) {
            res.append(words.get(i));
            if (i != m - 1)
                res.append(spcs);
        }
        while (res.length() != n)
            res.append(" ");
        return res.toString();
    }
}

C++

class Solution {
public:
    string reorderSpaces(string text) {
        int n = text.size(), spcnt = 0;
        vector<string> words;
        for (int i = 0; i < n; ) {
            if (text[i] == ' ' && ++i >= 0 && ++spcnt >= 0)
                continue;
            int j = i;
            while (j < n && text[j] != ' ')
                j++;
            words.emplace_back(text.substr(i, j - i)); // 单词
            i = j;
        }
        string res;
        int m = words.size(), dis = spcnt / max(m - 1, 1);
        string spcs = ""; // 两单词之间的空格
        while (dis-- > 0)
            spcs += " ";
        for (int i = 0; i < m; i++) {
            res += words[i];
            if (i != m - 1)
                res += spcs;
        }
        while (res.size() != n)
            res += " ";
        return res;
    }
};

Rust

impl Solution {
    pub fn reorder_spaces(text: String) -> String {
        let spcnt = text.chars().filter(|&c| c == ' ').count();
        let words: Vec<String> = text.split_whitespace().map(|s| s.to_string()).collect();
        let mut res = String::new();
        if words.len() == 1 {
            res.push_str(&words[0]);
            res.push_str(&" ".repeat(spcnt));
            return res
        }     
        for i in 0..words.len() {
            res.push_str(&words[i]);
            res.push_str(&" ".repeat(
                if i < words.len() - 1 {
                    spcnt / (words.len() - 1)
                }
                else {
                    spcnt - spcnt / (words.len() - 1) * (words.len() - 1)
            }));
        }
        res
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论