Length of Last Word
2016-07-25 19:39
423 查看
Description:
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.
分析:
从后向前查找即可
代码:
测试:
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.
分析:
从后向前查找即可
代码:
#include <iostream> #include <string> using namespace std; int LengthOfLastWord(string str) //从后向前读 { int len = str.size(); int LastWordLen = 0; int i = len - 1; while ( i > 0 && str[i] == ' ') //跳过空格 --i; while (i > 0 && str[i] != ' ') { i--; LastWordLen++; } return LastWordLen; } int main() { string s = "Hello World "; string s2 = " "; string s3 = " Hello,World "; cout << LengthOfLastWord(s) << endl; cout << LengthOfLastWord(s2) << endl; cout << LengthOfLastWord(s3) << endl; system("pause"); return 0; }
测试:
相关文章推荐
- Android官方数据绑定框架DataBinding
- 文档说明
- Volley 的 小实例
- 实时路况分析:不同路段车速预测、推荐(距离、时间、路况)最优路径
- codeforces 700C Break Up 暴力枚举边+边双缩点(有重边)
- RDD简介
- JavaScript实现点击(按钮)实现添加css样式
- java核心API
- Android下logcat用法详解
- 编译安装 LAMP
- 利用连续点灯定位汇编代码的错误
- ubuntu系统下使用锐捷上网的方法——特快
- java的IO知识点
- 【POJ】3253 - Fence Repair(贪心 & 优先队列)
- leetcode 83. Remove Duplicates from Sorted List
- 经管类科目
- jvm
- Service的是那种模式
- 【转】关于使用Android6.0编译程序时,出现getSlotFromBufferLocked: unknown buffer: 0xac0f8650问题的解释
- Mybatis JdbcType与Oracle、MySql数据类型对应列表