058 - Length of Last Word
2015-11-27 08:34
549 查看
Given a string s consists of upper/lower-case alphabets and empty space characters
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 =
return
int lengthOfLastWord(char* s)
{
while(*s == ' ') s++;
int slen = strlen(s);
if (!s || !slen) return 0;
char *last = s + slen - 1;
while (last - s > 0 && *last == ' ') last--;
if (last == s) return *last == ' '? 0:1;
last[1] = '\0';
char *lastspace = strrchr(s, ' ');
if (!lastspace) return strlen(s);
return strlen(lastspace + 1);
}
' ', 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.
int lengthOfLastWord(char* s)
{
while(*s == ' ') s++;
int slen = strlen(s);
if (!s || !slen) return 0;
char *last = s + slen - 1;
while (last - s > 0 && *last == ' ') last--;
if (last == s) return *last == ' '? 0:1;
last[1] = '\0';
char *lastspace = strrchr(s, ' ');
if (!lastspace) return strlen(s);
return strlen(lastspace + 1);
}
相关文章推荐
- Rotation Matrix
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- 第13周上机实践项目 - 验证算法(5)拓扑排序算法验证
- perl对称加密解密
- 第十三周上机实践—项目1(4)—Floyd算法验证
- 057 - Insert Interval
- 第十三周--项目1Prim算法
- 程序员的建议
- 第十三周 项目一(4)Floyd算法验证(使用图3作为测试用例)
- 056 - Merge Intervals
- 第七周项目4-队列数组
- linux解压多个文件
- 在程序员的眼里,用户是这样使用他们开发的软件的
- linux解压多个文件
- Protocol and Delegate协议和代理
- 第13周 项目5-拓扑排序算法验证
- 第十二周项目2操作用邻接表存储的图
- 第12周项目2 操作用邻接表存储
- 第十一周 项目1-1 二叉树的层次遍历算法
- iOS学习之分段Table View的使用(Grouped样式表格)