Java Solution


  • 0
    R
    class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            
            List<String> res = new ArrayList<>();
            if(words.length == 0) {
                res.add("");
                return res;
            }
            int available = maxWidth;
            int wordLength = 0;
            List<String> lineWord = new ArrayList<>();
            for(int i = 0; i < words.length; i++) {
                String eachWord = words[i];
                if(eachWord.length() > available) {
                    res.add(formatLine(lineWord, maxWidth, wordLength));
                    lineWord.clear();
                    wordLength = 0;
                    available = maxWidth;
                }
                wordLength += eachWord.length();
                lineWord.add(eachWord);
                available -= eachWord.length() + 1;    
            }
            if(lineWord.size() != 0) {
                String lastLine = "";
                for(int i = 0; i < lineWord.size(); i++) {
                    lastLine += lineWord.get(i);
                    if(i != lineWord.size()-1)  lastLine += " ";
                }
                while(lastLine.length() < maxWidth)     lastLine += " ";
                res.add(lastLine);
            }
            return res;
        }
        
        public String formatLine(List<String> lineWord, int maxWidth, int wordLength) {
            int numOfwhiteSpace = maxWidth - wordLength;
            StringBuilder sb = new StringBuilder();
            if(lineWord.size() == 0)    return "";
            if(lineWord.size() == 1) {
                sb.append(lineWord.get(0)).append(getConsecutiveSpace(numOfwhiteSpace));
                return sb.toString();
            }
            int evenIntervalNum = numOfwhiteSpace / (lineWord.size()-1);
            int numOfleftOver = numOfwhiteSpace % (lineWord.size()-1);
            for(int i = 0; i < lineWord.size(); i++) {
                String eachWord = lineWord.get(i);
                sb.append(eachWord);
                if(i != lineWord.size()-1) {
                    if(numOfleftOver > 0) {
                        sb.append(getConsecutiveSpace(evenIntervalNum+1));
                        numOfleftOver--;
                    }
                    else sb.append(getConsecutiveSpace(evenIntervalNum));
                }
            }
            return sb.toString();
        }
        
        public String getConsecutiveSpace(int n) {
            String s = "";
            while(n-->0) {
                s += " ";
            }
            return s;
        }
    }
    

Log in to reply
 

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