LintCode 422 最后一个单词的长度

描述
给定一个字符串, 包含大小写字母、空格 ’ ',请返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

一个单词的界定是,由字母组成,但不包含任何的空格。

样例
样例 1:

输入:"Hello World"
输出:5

样例 2:

输入:""
输出:0

样例 3:

输入:"LintCode"
输出:8

题解

class Solution {
    
    
public:
    /**
     * @param s: A string
     * @return: the length of last word
     */
    int lengthOfLastWord(string &s) {
    
    
        // write your code here
        int count=0;

        if( s.length()==0 ){
    
    
            return 0;
        }

        for( int i=s.length()-1; i>=0; i-- ){
    
    
            if( s[i]!=' '){
    
    //最后一个字符不为空格时
                if( s[i-1]!=' '&&i!=0){
    
    //前一个字符不为空格或者字符串s只有一个单词
                count++;
                }else{
    
    
                    return ++count;
                }
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/m0_46161051/article/details/119948395
今日推荐