Solution by Penhaunt


  • 0
    P
    class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> ans = new ArrayList<>();
            List<String> tmp = new ArrayList<>();
            int tmpL=0;
            boolean cleared=false;
            for(String w: words) {
                cleared = false;
                int l = tmpL;
                int ll = w.length();
                if(l + ll + tmp.size() <= maxWidth) {
                    tmp.add(w);
                    tmpL += ll;
                    if(l + ll == maxWidth) {
                        fun(ans, tmp,maxWidth-tmpL);
                        cleared=true;
                        tmp = new ArrayList<>();
                        tmpL = 0;
                    }
                } else {
                    fun(ans, tmp,maxWidth-tmpL);
                    //cleared=true;
                    tmp = new ArrayList<>();
                    tmp.add(w);
                    tmpL = ll;
                }
            }
            if(!cleared) fun2(ans, tmp,maxWidth-tmpL);
            return ans;
        }
        public void fun2(List<String> ans, List<String> tmp, int rl) {
            String s = "";
            for (String t : tmp) {
                if (s.length() > 0) {
                    s += " ";
                    rl--;
                }
                s += t;
            }
            if (rl > 0) {
                s = s + repeat(" ", rl);
            }
            ans.add(s);
        }
    
        public void fun(List<String> ans, List<String> tmp, int rl) {
            int count = tmp.size();
            if(count==1){
                String s=tmp.get(0);
                s = s + repeat(" ", rl);
                ans.add(s);
                return;
            }
            int sc = rl/(count-1);
            if(sc*(count-1) < rl) sc++;
            String s = "";
            for(String t: tmp) {
                count--;
                s += t;
                if(sc<=rl) {
                    s = s + repeat(" ", sc);
                    rl -= sc;
                    //--
                    sc = count<=1?0:rl/(count-1);
                    if(sc*(count-1) < rl) sc++;
                } else {
                    s = s + repeat(" ", rl);
                    rl = 0;
                    //--
                    sc = count<=1?0:rl/(count-1);
                    if(sc*(count-1) < rl) sc++;
                }
            }
    
            ans.add(s);
        }
    
        public String repeat(String s, int c) {
            String ans="";
            while(c>0){
                c--;
                ans+=s;
            }
            return ans;
        }
    }
    
    

Log in to reply
 

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