58. 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.


题意:

根据给定的字符串(包括大小写的字母和空格),返回最后一个单词的长度。如果最后一个单词不存在,返回零。(自己加:如果最后的一个是空格,返回前一个单词长度即可)


解题:

1)如果字符串为空,返回零。

2)获取字符串的长度,开始逐个读取字符串。如果碰到的是字母,那么size加一,登记单词长度;如果碰到是空格,置size为零,代表新单词重新开始计数。

3)如果最后一个为空格,那个置size为零前保留值在prev中。只有在size不为零的情况下才会把size保留在prev中,否则出现连续两个空格的情况,会把prev置为零的。


int lengthOfLastWord(char* s) 
{
    if ( !s )
    {   
        return 0;
    }
    
    int len = strlen( s );
    
    int cnt = 0;
    int size = 0;
    int prev = 0;
    for ( cnt = 0; cnt < len; cnt++ )
    {   
        if ( *( s + cnt ) == ' ' )
        {   
            if ( size )
            {   
                prev = size;
            }   
            size = 0;
        }   
        else
        {   
            size += 1;
        }   
    }
    
    return size == 0 ? prev : size;
}