[LeetCode] Length of Last Word 字符串查找
2024-08-31 06:04:47
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
.
Hide Tags
这题比较简单,只是可能前面有空格,后面有空格。- -
算法逻辑:
- 排除最后的空格
- index 从后往前查第一个空格。
- 返回长度。
#include <iostream>
#include <cstring>
using namespace std; class Solution {
public:
int lengthOfLastWord(const char *s) {
int n = strlen(s);
if(n <) return ;
int idx=n-;
while(idx>=&&s[idx]==' ') idx--;
n = idx+;
while(idx>=){
if (s[idx]==' ') break;
idx --;
}
// if(idx<0) return 0;
return n - idx -;
}
}; int main()
{
char s[] = " 12 ";
Solution sol;
cout<<sol.lengthOfLastWord(s)<<endl;
return ;
}
最新文章
- C#抽象类
- javascript 分页组件
- JS识记
- text .global_start 和_start
- Springmvc中 同步/异步请求参数的传递以及数据的返回
- 2015 UESTC Winter Training #8【The 2011 Rocky Mountain Regional Contest】
- PHP实现队列(Queue)数据结构
- iwebshop中的增删改查
- 跨过Nginx上基于uWSGI部署Django项目的坑
- Linux 链接详解----静态链接实例分析
- mysql中float类型使用总结
- 大话RabbitMQ 基础入门
- VUE中的v-show和v-if
- Codeforces.741D.Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths(dsu on tree 思路)
- NFS 网络文件系统制作
- 记unit of work与事务提交
- Mybatis分页查询与动态SQL
- 代码收藏系列--jquery--筛选器、事件绑定技巧
- DER编码简介
- Linux下改动Matlab配置文件支持C++ 11标准以生成mex