6ms Simple C solution.


  • 0
    S
    int wordsTyping(char** sentence, int sentenceSize, int rows, int cols) {
     
        int i=0;
        char *tmp;
       
        int total_len=0;
        
         while(i<sentenceSize)
         {
             total_len+=strlen(sentence[i]);
             i++;
         }
       //Space in the beginning plus in between words
        total_len = total_len+sentenceSize+1;
    
        tmp = (char *)malloc(sizeof(char)*total_len);
        //tmp pointer would have moved forward after the first while loop.So store initial address
        char *orig=tmp;
        i=0;
        //Store the actual sentence to be printed in a char array
        while(i<sentenceSize)
        {
            sprintf(tmp," %s",sentence[i]);
            tmp = tmp+strlen(sentence[i])+1;
            i++;
        }
        
        int actual_len = strlen(orig);
        int start=1;//since first char is a space we start with second index;
    
        for(int r=0;r<rows;r++,start++)
        {
            start+=cols;
            while(orig[start%actual_len]!=' ')
            {
                start--;
            }
        }
        
        return --start/actual_len;//since we started with start=1 reduce by one
    }
    

Log in to reply
 

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