long but easy to understand java solution


  • 1
    F
    public String justifyOneLine(String[] words, int maxWidth) {
            int n = words.length;
            int wordsLength = 0;
            for (String word : words) {
                wordsLength += word.length();
            }
            int spacesLength = maxWidth - wordsLength;
            if (n == 1) {
                char[] space = new char[spacesLength];
                Arrays.fill(space, ' ');
                return words[0] + String.valueOf(space);
            }
            int perSpace = spacesLength / (n - 1);
            int numOfExtra = spacesLength % (n - 1);
            char[] spaceArray = new char[perSpace];
            Arrays.fill(spaceArray, ' ');
            String space = String.valueOf(spaceArray);
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < n; i++) {
                result.append(words[i]);
                if (i < n - 1) {
                    result.append(space);
                    if (i < numOfExtra) {
                        result.append(" ");
                    }
                }
            }
            return result.toString();
        }
    
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> list = new ArrayList<>();
            int from = 0, to, counter = -1, n = words.length;
            for (int i = 0; i < n; i++) {
                counter += (words[i].length() + 1);
                if (counter >= maxWidth) {
                    to = counter == maxWidth ? i + 1 : i--;
                    list.add(justifyOneLine(Arrays.copyOfRange(words, from, to), maxWidth));
                    from = to;
                    counter = -1;
                }
            }
            if (from < n) {
                StringBuilder sb = new StringBuilder();
                for (int i = from; i < n; i++) {
                    if (i > from) {
                        sb.append(" ");
                    }
                    sb.append(words[i]);
                }
                char[] spacesArray = new char[maxWidth - sb.length()];
                Arrays.fill(spacesArray, ' ');
                sb.append(String.valueOf(spacesArray));
                list.add(sb.toString());
            }
            return list;
        }

  • 0
    G

    Could you explain this line?

    to = counter == maxWidth ? i + 1 : i--;
    

    Why do we still need to do "i--" given that "Arrays.copyOfRange(words, from, to)" will not include "to"?

    Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.