Length of Last Word

Q: 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.

A: length记录当前单词长度(空格看做长度为0),prevLength记录(前一个单词长度)。

如果length>0, 最后一个单词长度为length,否则为prevLength;

给prevLength赋值的时候要考虑空格连续的情况:如果length = 0, 说明遇到连续空格,不应该给prevLength赋值。

    int lengthOfLastWord(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int length = 0;
        int  prevLength = 0; 
        const char *cur = s;
        while(*cur!='\0')
        {
            if(*cur!=' ')
              length++;
            else
            {
                prevLength = (length>0?length:prevLength);
                length = 0;
            }
            
            cur++;
        }
        
        return (length>0?length:prevLength); 
    }

  

posted @ 2013-06-16 17:37  summer_zhou  阅读(151)  评论(0编辑  收藏  举报