[Leetcode] Length of last word 最后一个单词的长度
2024-08-27 07:03: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",
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;
}
};
最新文章
- JAVA中的类和接口
- 上下联动,右侧按钮过多poper展示
- 加载ComboBox控件
- Linux EOF使用
- 互联网+医疗(FW)
- php输出错误信息
- 一个简单的TestNG例子
- Codeforces 420 B. Online Meeting
- OpenStack及其构成简介
- 关闭eclipse自动弹出console的功能
- Google 视频编码格式 VP9 究竟厉害在哪里
- ImportError: No module named 'BaseHTTPServer':解决方案
- hi3531 SDK 编译 kernel, 修改 参数
- SSM-SpringMVC-03:SpringMVC执行流程一张有意思的图
- Doctirne---查询更新等操作
- 20190402Linux进阶命令week1.2
- AWS免费云服务套餐申请步骤及常见问题
- Practical Vim 第一章 &; 第二章
- 初识thinkphp(1)
- LeetCode Anagrams My solution