Got AC after thousands of trials


  • 0
    Z
    public class Solution {
    public List<String> fullJustify(String[] words, int L) {
        LinkedList<String> queue = new LinkedList<String>(Arrays.asList(words));
        ArrayList<String> res = new ArrayList<String>();
        int max = 0;
        if (words.length == 0) return res;
        for (int i = 0; i < words.length; i++){
            max = Math.max(max, words[i].length());
        }
        if (max == 0){
            String str = "";
            for (int i = 0; i < L; i++)
                str += " ";
            res.add(str);
            return res;
        }
        // Main loop
        while(!queue.isEmpty()){
            int sum = 0;
            int num = 0;
            String str = "";
            while (true){
                if (!queue.isEmpty()){
    				if (sum + queue.getFirst().length() <= L){
    					String temp = queue.poll() + " ";
    					str = str + temp;
    					sum += temp.length();
    					num++;
    				}
    				else
    					break;
    			
    			}
    			else{                   //last line
    				if (sum > L)
    					str = str.substring(0,str.length()-1);
    				for (int i = 0; i < L-sum; i++)
    					str += " ";
    				res.add(str);
    				return res;
    			}
            }
            String[] list = str.split(" ");
            // Compute how many spaces between each word
            int total_len = 0;
            for (int i = 0; i < num; i++){
                total_len += list[i].length();
            }
            if (num == 1){                  //if there is only one word in a line    
            	String st = list[0];
            	int len = (L-st.length());
            	for (int i = 0; i < len; i++){
            		st += " ";
    		}
            	res.add(st);
            }
            else{                           //allocate space between each word according to the rule
    			int space_len = (L-total_len)/(num-1);
    			int more_space = (L-total_len)%(num-1);
    			String t = "";
    			for (int i = 0; i < more_space; i++){
    				t += list[i];
    				for (int j = 0; j < space_len; j++){
    					t += " "; 
    				}
    				t += " ";
    			}
    			for (int i = more_space; i < num-1; i++){
    				t += list[i];
    				for (int j = 0; j < space_len; j++){
    					t += " ";
    				}
    			}
    			t += list[num-1];
    			res.add(t);
    		}
        }
        return res;
    }

Log in to reply
 

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