C++ - Test case 10 - ["a","b","c","d","e"], 1 - expected same as output


  • 0
    T

    I see no difference between mine input and desired one...

    Input: ["a","b","c","d","e"], 1
    Output: ["a","b","c","d","e"]
    Expected: ["a","b","c","d","e"]

    Here is mine code (I know it's not optimal yet, I'm just looking for clues):

    class Solution {
    public:
    vector<string> fullJustify(vector<string> &words, int L) {
       vector<string> res;
       if (!L) { // IMHO empty res should returned
           res.push_back(""); // instead of one with empty element
           return res; // it's weird
       }
    
       vector<string> lin; // I know I can get rid of this later on and change this to index to have O(1)
       int siz = 0; // total length
       
       for(unsigned int i = 0; i < words.size(); ++i){
           if (siz + lin.size() + words[i].size() <= L + 1) {
               // adding word to current line
               lin.push_back(words[i]);
               siz += words[i].size();
           } else { // we don't have enough space for new word
               // fullfilling spaces to match line length
               if (lin.size() > 1) {
                   unsigned int j = 0;
                   while(siz < L){
                      lin[j] += " ";
                      j++;
                      j %= (lin.size() - 1);
                      siz++;
                   }
               } else {
                   lin[0].resize(' ', L);
               }
               // generating output
               string out;
               // adding words to output
               for(unsigned int j = 0; j < lin.size(); j++){
                   out += lin[j];
               }
               
               res.push_back(out);
                  
               // clearing line and adding a word
               lin.clear();
               lin.push_back(words[i]);
               siz = words[i].size();
           }
       }
       
       // last line - no justification
    
       if (lin.size()) {
         string out = lin[0];
         for(unsigned int i = 1; i < lin.size(); ++i){
           out += " ";
           out += lin[i];
         }
         while(out.size() < L) out += " ";
         res.push_back(out);
       }
    
        return res;
      }
    };

  • 0
    T

    One year later they've fixed printing output and added non-printable characters output (\x01). I've had wrong arguments in resize and extra +1 in if statement.


Log in to reply
 

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