concise C++ solution


  • 0
    U
    class Solution {
    public:
    int wordsTyping(vector<string>& sentence, int rows, int cols) {
        int cnt = 0;
        vector<int>sp;
        int sum = 0;
        for(auto s:sentence){sp.push_back(s.size());sum+=s.size();}
        int start = 0;
        int i = 0;
        while(i < rows)
        {
            // cycle start; 
            if(start == 0 and i != 0)
            {
                cnt = cnt*(rows/i);
                i = rows- (rows%i);
                if(i >= rows)break;
            }
            
            // number of cycles in one row
            int accum = (1 + cols)%(sum+sp.size())-1;
            cnt += (1 + cols)/(sum+sp.size());
            
            // collect all the remnants
            while(accum >= sp[start])
            {
                accum -= (1 + sp[start]);
                start = (start+1)%sp.size();
                if(start == 0)cnt++;
            }
            i++;
        }
        return cnt;
    }
    };
    

Log in to reply
 

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