[LeetCode] Length of Last Word

2014-11-24 02:00:34 · 作者: · 浏览: 3
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.
问题描述:给定一个字符串,它包含空格,返回这个字符串中最后一个单词的长度。
如果没有最后一个单词,则返回0,这里“没有最后一个单词”理解为没有单词。
由于参数给定的类型是const char *,因此,这题考察的是指针的操作。
用参数给定的s字符指针来遍历字符串,用一个int型整数来记录长度,当遍历的字符没有结束,也就是*s != 0时,就判断该字符是否为' '字符,如果是空格,就继续遍历把空格略去,当然在去掉空格的过程中,同样要判断是否还有字符,如果在这儿就没有字符了,就返回之前得到的单词的长度,如果后面还有字符,那么就需要将长度计数置为0,遍历完成后,返回长度。
class Solution {  
public:  
    int lengthOfLastWord(const char *s) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        int len = 0;  
          
        while(*s) {  
            if(*s == ' ') {  
                while(*s && *s == ' ')  
                    ++s;  
                if(*s == 0)  
                    return len;  
                len = 0;  
            }  
            ++len;  
            ++s;  
        }  
          
        return len;  
    }  
};