Test case for two-words justification


  • 0
    M

    My code below failed at this test case

    Input: ["What","must","be","shall","be."], 12
    Output: ["What must be","shall be."]
    Expected: ["What must be","shall be. "]

    I don't understand with two words "Shall", and "be.", why would the last Expected be left justified instead of fully justified?

    public List<String> fullJustify(String[] words, int L) {
    List<String> res = new LinkedList<String>();
    if(words == null || words.length == 0 || L < 0 ) return res;

            int start = 0, end = 0, spaces = 0, len = 0;
            while(end < words.length && start <= end){
                if(start == end) {// first word for the row
                    len = words[start].length();
                    end++;
                    continue;
                } else if(len + spaces + 1 + words[end].length() > L){// 1 for space
                    String line = buildLine(words, start, end, L - len);
                    res.add(line);
                    
                    start = end;
                    spaces = 0;
                    len = 0;
                } else {
                    len += words[end++].length();
                    spaces++;
                }
            }
            
            if(start < end){
                String line = buildLine(words, start, end, L - len);
                res.add(line);
            }
            
            return res;
        }
        
        String buildLine(String[] words, int start, int end, int spaces){
            StringBuilder sb;
            if (end - start == 1)
            {
                sb = new StringBuilder(words[start]);
                for (int i = 0; i < spaces; i++)
                {
                    sb.append(" ");
                }
    
                return sb.toString();
            }
    
            int dem = (int) Math.ceil((double) spaces / (double) (end - start - 1));
    
            sb = new StringBuilder();
            for(int i= start;i<end;i++){
                sb.append(words[i]);
                
                // build the spaces
                StringBuilder s = new StringBuilder();
                if(spaces >= dem){
                    
                    for(int k=0;k<dem;k++){
                        s.append(" ");
                    }
                    spaces -= dem;
    
                } else {
                    for(int k=0;k<spaces;k++){
                        s.append(" ");
                    }
                    
                    spaces = 0;
                }
                
                sb.append(s.toString());
            }
            
            return sb.toString();
        }

Log in to reply
 

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