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

approach 1

class Solution {
    public String reorderSpaces(String text) {
        int space = 0;
        int word = 0;
        List<String> ws = new ArrayList<>();
        StringBuilder last = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == ' ') {
                space++;
                ws.add(last.toString());
                last = new StringBuilder();
            } else if (i == 0 || text.charAt(i-1) == ' ') {
                word++;
                last.append(c);
            } else {
                last.append(c);
            }
        }

        if (last.length() != 0) {
            ws.add(last.toString());
        }

        int per = word == 1 ? space : space / (word-1);
        
        StringBuilder res = new StringBuilder();
        int cnt = word;
        for (String s : ws) {
            if (s.equals("")) {
                continue;
            }
            res.append(s);
            if (cnt == 1) {
                break;
            }
            cnt--;
            for (int i = 0; i < per; i++) {
                res.append(" ");
            }
        }
        int reminder  = word == 1 ? space : space % (word-1);
        for (int i = 0; i < reminder; i++) {
            res.append(" ");
        }

        return res.toString();
    }
}
Last Updated:
Contributors: jesse