【Leetcode】【Easy】Length of Last Word
2024-08-24 17:08:36
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
.
解题思路1:
遍历字符串,设置整形变量n,记录当前遍历到的无空格子串的长度,如果子串后遇到空格,且空格后再次遇到新的子串,则更新n,否则返回n;
注意:
本题容易忽略的是,返回最后一个子串的长度,不能简单想做遇到空格就重新计数,因为可能空格后不再有子串了,也就是最后一个子串结束后,字符串没有完,还有空格存在。因此要注意对这种情况进行判断。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.size();
int len_lw = ; for (int i = ; i < len; ++i) {
if (i != && s[i-] == ' ' && s[i] != ' ')
len_lw = ;
if (s[i] != ' ')
len_lw++;
} return len_lw;
}
};
解题思路2:
直接从后遍历字符串,先过滤尾部的空格,之后遍历的第一个子串长度就是要返回的结果。
class Solution {
public:
int lengthOfLastWord(const char *s) {
int len = strlen(s);
int sum = ; while (s[len-] == ' ')
len--; for (int i=len-; i>=; i--) {
if(s[i]!=' ')
sum++;
else
break;
} return sum;
}
};
附录:
1、C语言中的char* char const char 和C++ string的关系
2、C++中对字符串操作的函数总结
3、灵活运用字符串指针,多用指针操作,少用数组操作:
class Solution {
public:
int lengthOfLastWord(const char* s) {
int len = ; while (*s) {
if (*s++ != ' ')
++len;
else if (*s && *s != ' ')
len = ;
} return len;
}
};
最新文章
- 【Android】学习记录<;1>; -- 初识ffmpeg
- 北大OJ 1001题
- 移动端图片上传解决方案localResizeIMG先压缩后ajax无刷新上传
- fprintf, fscanf,printf,scanf使用时参数注意
- HDU1166-敌兵布阵(线段树)
- javascript AES加密 C#AES解密实现
- Cognitive Radio Emergency Networks – Requirements and Design
- hbase checkandput
- SQL IO监控
- Python之路:常用算法与设计模式
- yolov2训练ICDAR2011数据集
- [0] MVC&;MVP&;MVVM差异点
- MySQL5.6.36 linux rpm包安装配置文档
- Hive分区表动态添加字段
- Weex Ui - Weex Conf 2018 干货分享
- 阿里八八Alpha阶段Scrum(8/12)
- State of Serverless
- 【Java并发编程】:volatile变量修饰符
- 堆排序算法-python实现
- SugarCRM如何检查控制器权限?
热门文章
- B. Div Times Mod Round #528 (Div. 2)【简单数学】
- CSL 的字符串(思维+STL操作)
- Codeforces - 617E 年轻人的第一道莫队&#183;改
- h5列表页的性能优化
- opencv java小应用:比较两个图片的相似度
- Docker 命令详解(run篇)
- linux 密码复杂度设置
- QWebView使用
- C# 批量生成随机密码,必须包含数字和字母,并用加密算法加密
- 【Linux相识相知】计算机的组成、linux发行版和哲学思想、基础命令和目录结构(FHS)