Thursday, April 17, 2014

[LeetCode] Length of Last Word

Problem Statement (link):
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.
Analysis:
- Just traverse the char array until you hit NULL.
- Remember to reset the count once you hit a space char, iff it's not the last word.
- The logic I use to determine that it is NOT the last word, where we need to reset the count, is: 1) If current char is space char; 2) If the next char is not space char; 3) If the next char is not NULL.

e.g., string: "ab     cde    "

where we need to reset count when we hit the space before c, we shouldn't reset count when we hit spaces after e.

Code:
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        if (*s==NULL) return 0;
        int len=0;
        const char *cur=s;
        while(*cur!=NULL) {             if (*cur!=' ')                 len++;             if (*cur==' ' && *(cur+1)!=' ' && *(cur+1)!=NULL) // if there is a next word                     len=0;             cur++;         }         return len;     } };


No comments:

Post a Comment