Thursday, May 8, 2014

LeetCode: Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.


The solution is straight forward, just keep a count from the start and when there is a char before a space, we reset the count.

C++ Code:

/*
 * func: length_of_last_word
 * goal: get the length of the last word in the string
 * @param s: pointer to the string
 * return: length
 */
int length_of_last_word(const char *s){
    int result = 0;
    while(s != nullptr && *s != '\0'){
        //If current char is not space
        if(*s++ != ' '){
            ++result;
        }else if(*s != '\0' && *s != ' '){
            //If current char is space next char is not space
            result = 0;
        }
    }
    return result;
}

Python Code:

# func: get the length of the last word in the string
# @param s: input string
# @return: length
def length_of_last_word(s):
    words = s.strip().split(" ")
    return len(words[-1])

No comments:

Post a Comment