Simple Java Solution


  • 0
    C
    public class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> res = new ArrayList<String>();
            char[] spaces = new char[maxWidth];
            for (int i = 0; i < maxWidth; i++){
                spaces[i] = ' ';
            }
            for (int start = 0; start < words.length;){
                int len = words[start].length();
                int end = start + 1;
                for (; end < words.length && len + 1 + words[end].length() <= maxWidth; end++){
                    len += 1 + words[end].length();
                }
                StringBuilder newStr = new StringBuilder(maxWidth);
                newStr.append(words[start]);
                int slotNum = end - start - 1;
                start++;
                if (end != words.length && slotNum != 0){
                    int evenNum = (maxWidth - (len - slotNum)) / slotNum;
                    int leftNum = (maxWidth - (len - slotNum)) % slotNum;
                    while (start < end){
                        newStr.append(spaces, 0, evenNum);
                        if (leftNum > 0){
                            newStr.append(' ');
                            leftNum--;
                        }
                        newStr.append(words[start]);
                        start++;
                    }
                } else {
                    while (start < end){
                        newStr.append(' ');
                        newStr.append(words[start]);
                        start++;
                    }
                    newStr.append(spaces, 0, maxWidth - newStr.length());
                }
                
                res.add(newStr.toString());
            }
            return res;
        }
    }
    

Log in to reply
 

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