What's wrong with my intuitive C code?


  • 0
    D

    int lengthOfLastWord(char* s) {

    int length= strlen(s);
    if (length==0) {
        return 0;
    }
    
    int lastlen = 0;
    while (length >0 && s[length] != ' ') {
        lastlen ++; 
        length --;
      }
    return lastlen; 
    

    }

    Outcome:

    Input:
    " "
    Output:
    1
    Expected:
    0


  • 0
    S

    You need to account for spaces at the end of the string or a string of only spaces in this case
    so you need a loop before the one that increments the lastlen return value that will move your comparisons to the last non space character, or the beginning of the string


Log in to reply
 

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