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",
return5.

思路:要求最后一个单词的长度,首先想到的当然是从后往前开始遍历,若遇到空格或者下标等于0了,就返回单词的个数就行,但是,这样想忽略了一个问题,若是,字符串最后有空格怎么办?如: s ="Hello World    ",所以应该是从后往前遍历的时候,先跳过空格,直到遇到第一个非空格的字符,才开始计数。代码如下:

 class Solution {
public:
int lengthOfLastWord(const char *s)
{
int res=;
int len=strlen(s);
if(s==NULL) return ;
int i=len-;
while(s[i]==' ')
i--;
while(s[i] !=' '&&i>=)
{
i--;
res++;
}
return res;
}
};

最新文章

  1. JAVA中的类和接口
  2. 上下联动,右侧按钮过多poper展示
  3. 加载ComboBox控件
  4. Linux EOF使用
  5. 互联网+医疗(FW)
  6. php输出错误信息
  7. 一个简单的TestNG例子
  8. Codeforces 420 B. Online Meeting
  9. OpenStack及其构成简介
  10. 关闭eclipse自动弹出console的功能
  11. Google 视频编码格式 VP9 究竟厉害在哪里
  12. ImportError: No module named 'BaseHTTPServer':解决方案
  13. hi3531 SDK 编译 kernel, 修改 参数
  14. SSM-SpringMVC-03:SpringMVC执行流程一张有意思的图
  15. Doctirne---查询更新等操作
  16. 20190402Linux进阶命令week1.2
  17. AWS免费云服务套餐申请步骤及常见问题
  18. Practical Vim 第一章 & 第二章
  19. 初识thinkphp(1)
  20. LeetCode Anagrams My solution

热门文章

  1. ECSHOP和SHOPEX快递单号查询韵达插件V8.6专版
  2. Yii 2.0.6 - 从入口到Action执行
  3. Excel学习路径总结
  4. (转) Sqoop使用实例讲解
  5. SpringCloud项目,接口调用返回http 500 - Internal Server Error的错误
  6. Cyclone IV器件的逻辑单元和逻辑阵列快
  7. Linux的系统安全设置Shell脚本
  8. MySQL数据库服务器逐渐变慢分析
  9. Android开发免费类库和工具集合
  10. [B2B、B2C、C2C] 区别介绍