Length of Last Word

来源:互联网 发布:免费印刷排版软件 编辑:程序博客网 时间:2024/04/29 18:07

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.

计算给定字符串最后一个单词的长度。

常见的方法是从末尾开始算,直接算出最后一个单词的长度。这里介绍一个不常见的直接从头开始检测的方法:

定义两个变量count和last,count计算当前单词的长度,只要count>0则将count赋值给last,如果当遇到空格则将count赋值为0,count为0时last还是赋值为last,以免字符串最后一个字符为空格的情况。代码如下:

class Solution {public:    int lengthOfLastWord(const char *s) {        int count=0,last=0;          while(*s!='\0') {              count=*s ==' '?0:count+1;              last=count>0?count:last;              s++;          }          return last;      }};


<pre name="code" class="cpp">


0 0