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.

分析:

简单模拟思想。去掉尾部的空格并统计是字符的个数直到再次遇到空格就停止统计

class Solution {
public:
int lengthOfLastWord(string s) {
int strLen=s.size();
int len=0;
int i=0;
while(s[strLen-i-1]==' ')
i++;
for(;i<strLen;i++)
{
if(s[strLen-i-1]>='A'&&s[strLen-i-1]<='Z' || s[strLen-i-1]>='a'&&s[strLen-i-1]<='z' )
len++;
else
break;
}
return len;
}
};

或者用STL来写:

class Solution {
public:
int lengthOfLastWord(string s) {
int i = s.find_last_not_of(' ');
return (i == string::npos) ? 0 : (i - s.find_last_of(' ', i));
}
};

注:本博文为EbowTang原创。兴许可能继续更新本文。假设转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50498956

原作者博客:http://blog.csdn.net/ebowtang

最新文章

  1. KVO 键值观察者
  2. VS2012使用中容易出现的小问题(长期更新,错多少记多少)
  3. 设置MySQL服务自动运行
  4. 使用Oracle的审计功能记录连接数据库登录失败的用户信息
  5. 解决git客户端MINGW32下的“Could not open a connection to your authentication agent.”
  6. HTML+CSS学习笔记 (11) - CSS盒模型
  7. Winfrom 开发系统导航菜单
  8. XFdtd 7.3.2发布增强生物电磁学中的核磁共振功能
  9. WebForm 三级联动
  10. 关于HBuilder的一些使用技巧。
  11. 第一个只出现一次的字符字符(python)
  12. 关于linux中SSH爆破总结
  13. 各种形式的熵函数,KL距离
  14. MicroMsg.SDK.WXApiImplV10: register app failed for wechat app signature check failed
  15. 20180705 fragment
  16. Daily Scrum 11.10
  17. Redis有序集内部实现原理分析
  18. 各种GIT代码托管工具比较
  19. vue路由vue-route
  20. 修复Ubuntu的引导

热门文章

  1. SQL Server Backup &amp; Restore
  2. 【译】Asp.Net Identity Cookies 格式化-中英对照版
  3. [转载] Redis资料汇总专题
  4. python 有关datetime时间日期 以及时间戳转换
  5. RabbitMQ之Helloworld
  6. JavaScript中的内存泄漏以及如何处理
  7. 隐藏17年的Office远程代码执行漏洞(CVE-2017-11882)
  8. 你好 JSONP !!!!
  9. IIFE(立即执行函数表达式)
  10. 使用Angular Router导航基础