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
- 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
- TCP/IP、Http的区别
- libsvm, liblinear, svmlight简介
- Create workflow with a content type association
- Android下拉刷新研究(—)
- 小P寻宝记——好基友一起走
- Length of Last Word
- An error was encountered while running(Domain=LaunchSerivcesError, Code=0)
- 转载大神IOS开发系列【15】--音频视频使用
- HDU 1176 免费馅饼 (DP)
- shopex使用经验
- 创建一个静态链表,通过输入元素及位置插入一个元素,然后通过输入删除元素的位置删除元素。
- tomcat部署项目去掉ip和域名
- 基于AWS的媒体共享系统架构
- 创建一个完整的CCS工程(基于F2812)