leetcode Question 41: Length of Last Word

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.

Updated 201309:

class Solution {
public:
    int lengthOfLastWord(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int sz = strlen(s);
        if (sz==0){return 0;}
        int res=0;
        for (int i=sz-1;i>=0;i--){
            if (s[i]!=' '){res++;}
            else{ if (res>0){return res;} }
        }
        return res;   
    }
};





Old version:
Analysis:
Simple problem, but be careful with the special cases. Such as:  "  " , "  day" ,"day   ",etc.
The basic idea is search from the end to the start, if the current letter is A-Z a-z, count the word, until find the  space or meet the start, return the length.

Source Code:

class Solution {
public:
    int lengthOfLastWord(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = strlen(s);
        if (len==0) {return 0;}
        int res=0;
        bool fl=false;
        while (len>=0){
            if ( (s[len]>='a' && s[len]<='z')||(s[len]>='A' && s[len]<='Z') ){fl=true; res=res+1;}
            if (s[len]==' ' && fl) { return res;}
            len--;
        }
        if (fl) {return res;}
        if (!fl){return 0;}
    }
};

No comments:

Post a Comment