Length of Last Word
来源:互联网 发布:顶级定制晚礼服 知乎 编辑:程序博客网 时间:2024/05/17 07:22
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.
分析:
从后向前查找即可
代码:
#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;}
测试:
0 0
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- Length of Last Word
- 【cpp面向对象编程学习笔记】Class经典分类(1)without pointer member(s)
- java核心API
- JavaScript实现点击(按钮)实现添加css样式
- Volley 的 小实例
- 文档说明
- Length of Last Word
- 设计模式学习笔记--设计模式概述
- POJ 1151 Atlantis
- u3d fbx动画模型生成Animator Controller和Prefab工具脚本
- Python 之 日志logging 之 2
- java基础Day04
- 四大组件之其三
- 排序算法(1)插入排序的算法分析
- solr6.1 安装,开发demo