Can anyone help me with C solution?


  • 0
    Y
    char** findWords(char** words, int wordsSize, int* returnSize) {
    
    bool isRow1 = false;
    
    bool isRow2 = false;
    
    bool isRow3 = false;
    
    char** returnWords = (char**) malloc(returnSize);
    
    int returnWordsIndex = 0;
    
    for (int i = 0; i < wordsSize; ++i) {
        for (int j = 0; j < strlen(words[i]); ++j) {
            if (toupper(words[i][j]) == 'Q' || toupper(words[i][j]) == 'W' || toupper(words[i][j]) == 'E' || toupper(words[i][j]) == 'R' || toupper(words[i][j]) == 'T' || toupper(words[i][j]) == 'Y' || toupper(words[i][j]) == 'U' || toupper(words[i][j]) == 'I' || toupper(words[i][j]) == 'O' || toupper(words[i][j]) == 'P') {
                isRow1 = true;
                
                if (isRow2 || isRow3) {
                    break;
                }
            }
            
            if (toupper(words[i][j]) == 'A' || toupper(words[i][j]) == 'S' || toupper(words[i][j]) == 'D' || toupper(words[i][j]) == 'F' || toupper(words[i][j]) == 'G' || toupper(words[i][j]) == 'H' || toupper(words[i][j]) == 'J' || toupper(words[i][j]) == 'K' || toupper(words[i][j]) == 'L') {
                isRow2 = true;
                
                if (isRow1 || isRow3) {
                    break;
                }
            }
            
            if (toupper(words[i][j]) == 'Z' || toupper(words[i][j]) == 'X' || toupper(words[i][j]) == 'C' || toupper(words[i][j]) == 'V' || toupper(words[i][j]) == 'B' || toupper(words[i][j]) == 'N' || toupper(words[i][j]) == 'M') {
                isRow3 = true;
                
                if (isRow1 || isRow2) {
                    break;
                }
            }
            
            if (j == strlen(words[i]) - 1) {
                returnWords[returnWordsIndex] = (char*) malloc(strlen(words[i]));
                strcpy(returnWords[returnWordsIndex], words[i]);
                ++returnWordsIndex;
            }
        }
        
        isRow1 = false;
        isRow2 = false;
        isRow3 = false;
    }
    
    return returnWords;
    

    }


  • 0
    C

    The first thing that jumped out at me is this line:

    char** returnWords = (char**) malloc(returnSize);
    

    You are passing an int pointer to malloc() instead of a size_t or int value. You don't want to use the value of returnSize either because this is 0 to start with. We need to update this value to indicate how many words are being returned.

    For this problem you can pass wordsSize to malloc() and it will work fine. If the list of words were really long you may not want to do this, but for this problem's test cases it's not a big deal.


Log in to reply
 

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