58.Length of last word

Given astrings consists of upper/lower-casealphabetsandempty space characters' ',returnthe length of last word in the string.

If the last word doesnotexist,return0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"

Output:

5

求句末单词的长度

代码:

class Solution {

public:

    int lengthOfLastWord(string s) {

int right=s.length()-1,res=0;

    if(s.length()==0)

        return 0;

      while(right>=0 && s[right]==' ')

      {

          right--;

      }

    while (right>=0 && s[right]!=' ') {

        res++;

        right--;

    }

    return res;

    }

};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容