My solution, but why can't pass "a " test case


  • 1
    M

    Run the codes with VC6, it works well.But can't pass test case "a "

    int lengthOfLastWord(const char *s) {
        int last = 0;
        int length = 0;
    
        while('\0' != s[last])
        {
            if (' ' == s[last])
            {
                length = 0;
            }
            else
            {
                length++;
            }
            last++;
        }
    
        return length;
    }

  • 1
    P

    I think your answer to "a " is 0, but the result is actually 1, as the length of word "a" is 1.


  • 0
    G

    Problem is that you directly reset the length when you encounter spaces.
    Try a bottom-up approach, and absorb all the spaces at the end.


Log in to reply
 

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