C++ find repeat pattern


  • 0
    B

    this solution is somewhat similar to the questions that find repeated substring in another string

    class Solution {
    public:
        int wordsTyping(vector<string>& sentence, int rows, int cols) {
            int len = sentence.size(), count = 0;
            vector<int>round(len+1, 0), sizes(len, 0), idx(len, -1);
            for(int i = 0; i < len; i++) sizes[i] = sentence[i].size();
            for(int row = 0; row < rows; row++)
            {
                int id = cols;
                if(idx[count%len] > cols) return 0;
                while(id >= sizes[count%len])
                {
                    id -= sizes[count%len] + 1;
                    count++;
                }
                round[row] = count;
                if(idx[(count-1) % len] >= 0)
                {//found pattern
                    int lastRow = idx[(count-1) % len];
                    int repeat = (rows - lastRow - 1)/(row - lastRow);
                    int ret = (count - round[lastRow])*repeat;
                    ret += round[lastRow + (rows - lastRow - 1)%(row - lastRow)];
                    return ret/len;
                }
                idx[(count-1) % len] = row;
            }
    
            return round[rows-1]/len;
        }
    };

Log in to reply
 

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