package leetcode;

/**
 * https://leetcode.com/problems/rearrange-spaces-between-words/
 */
public class Problem1592 {
    public String reorderSpaces(String text) {
        // TODO
        return null;
    }

    public static void main(String[] args) {
        Problem1592 prob = new Problem1592();
        System.out.println(prob.reorderSpaces("  this   is  a sentence ")); // "this   is   a   sentence"
        System.out.println(prob.reorderSpaces(" practice   makes   perfect")); // "practice   makes   perfect "
        System.out.println(prob.reorderSpaces("hello   world")); // "hello   world"
        System.out.println(prob.reorderSpaces("  walks  udp package   into  bar a")); // "walks  udp  package  into  bar  a "
        System.out.println(prob.reorderSpaces("a")); // "a"
    }
}

@@ -171,622 +171,742 @@
     
-// TODO%0A        return null;%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem1592 prob = new Problem1592();%0A        System.out.println(prob.reorderSpaces(%22  this   is  a sentence %22)); // %22this
+int totalSpaces = 0;%0A        for (char c : text.toCharArray()) %7B%0A            if (c == ' ') %7B%0A                totalSpaces++;%0A            %7D%0A        %7D%0A        String%5B%5D words = text.trim().split(%22%5C%5Cs+%22);%0A        int spaces = words.length - 1 %3E 0 ? totalSpaces / (words.length - 1) : 0;%0A        int extraSpaces = words.length - 1 %3E 0 ? totalSpaces %25 (words.length - 1) : totalSpaces;%0A
    
-is
    
-a
   
- sentence%22%0A        System.out.println(prob.reorderSpaces(%22 practice   makes   perfect%22)); // %22practice   makes   perfect %22%0A        System.out.println(prob.reorderSpaces(%22hello   world%22)); // %22hello   world%22%0A        System.out.println(prob.reorderSpaces(%22  walks  udp package   into  bar a%22)); // %22walks  udp  package  into  bar  a %22%0A        System.out.println(prob.reorderSpaces(%22a%22)); // %22a%22
+StringBuilder answer = new StringBuilder();%0A        for (String word : words) %7B%0A            if (answer.length() == 0) %7B%0A                answer.append(word);%0A            %7D else %7B%0A                answer.append(%22 %22.repeat(spaces)).append(word);%0A            %7D%0A        %7D%0A        answer.append(%22 %22.repeat(extraSpaces));%0A        return answer.toString();
 %0A   

Solve exercise 1592