[LeetCode] Length of Last Word
2014-01-02 07:56
309 查看
问题:
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
分析:
简单的一道题,没有任何技巧。注意一下边界等小问题即可。
代码:
class Solution {
public:
int lengthOfLastWord(const char *s) {
int index = strlen(s) - 1;
while (index >= 0 && s[index] == ' ')
index --;
int result = 0;
for(; index >= 0; index --, result ++) {
if (s[index] == ' ')
break;
}
return result;
}
};
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.
分析:
简单的一道题,没有任何技巧。注意一下边界等小问题即可。
代码:
class Solution {
public:
int lengthOfLastWord(const char *s) {
int index = strlen(s) - 1;
while (index >= 0 && s[index] == ' ')
index --;
int result = 0;
for(; index >= 0; index --, result ++) {
if (s[index] == ' ')
break;
}
return result;
}
};
相关文章推荐
- 动易2006序列号破解算法公布
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- C#数据结构与算法揭秘二
- 浅析STL中的常用算法
- JavaScript 组件之旅(二)编码实现和算法
- php 面试碰到过的问题 在此做下记录
- asp.net 面试+笔试题目第1/2页
- asp.net 面试 笔试题目[附答案]第1/3页
- 将15位身份证补全为18位身份证的算法示例详解
- C++算法系列之日历生成的算法代码
- 1 2 3 4 5 6 7 8 9 = 110的java实现
- Sedgewick之巨著《算法》,与高德纳TAOCP一脉相承
- 【代码】Pythonの代码片段
- 面试:(设计,架构)
- STL中算法
- 数据结构&算法学习
- 算法的时间复杂度
- 算法导论:选择排序的原理与实现
- PHP实现四种常用的排序算法
- 图解插入排序算法