Saturday, April 4, 2015

LeetCode [58] Length of Last Word

 58. Length of Last Word

Easy

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    int lengthOfLastWord(const char *s) {
        int count = 0;
        int res = 0;
        while(*s!='\0'){
            if(*s!=' '){
                count++;
            }else{
                if(count) res = count;
                count=0;
            }
            s++;
        }
        return count>0?count:res;
    }
};

No comments:

Post a Comment