2013.12.21 01:48
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
.
Solution:
Search for the start and end position of the last word, the length is (end - start).
Note that there might be NO last word at all, return 0 then.
Time complexity is O(n), where n is the length of the string. Space complexity is O(1).
Accepted code:
1 // 1WA, 1AC 2 class Solution { 3 public: 4 int lengthOfLastWord(const char *s) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 if(s == nullptr){ 8 return 0; 9 } 10 11 int len = strlen(s); 12 13 if(len <= 0){ 14 return 0; 15 } 16 17 int i, j; 18 19 i = len - 1; 20 while(i >= 0 && s[i] == ' '){ 21 --i; 22 } 23 ++i; 24 25 // 1WA, index is wrong, not j = i, but j = i - 1 26 j = i - 1; 27 while(j >= 0 && s[j] != ' '){ 28 --j; 29 } 30 ++j; 31 if(i < 0 || j < 0 || i < j){ 32 return 0; 33 }else{ 34 return i - j; 35 } 36 } 37 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)