Length of Last Word
2013-06-16 17:37
295 查看
Q: 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
A: length记录当前单词长度(空格看做长度为0),prevLength记录(前一个单词长度)。
如果length>0, 最后一个单词长度为length,否则为prevLength;
给prevLength赋值的时候要考虑空格连续的情况:如果length = 0, 说明遇到连续空格,不应该给prevLength赋值。
' ', 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.
A: length记录当前单词长度(空格看做长度为0),prevLength记录(前一个单词长度)。
如果length>0, 最后一个单词长度为length,否则为prevLength;
给prevLength赋值的时候要考虑空格连续的情况:如果length = 0, 说明遇到连续空格,不应该给prevLength赋值。
int lengthOfLastWord(const char *s) { // Start typing your C/C++ solution below // DO NOT write int main() function int length = 0; int prevLength = 0; const char *cur = s; while(*cur!='\0') { if(*cur!=' ') length++; else { prevLength = (length>0?length:prevLength); length = 0; } cur++; } return (length>0?length:prevLength); }
相关文章推荐
- leetcode 58 Length of Last Word
- [Leetcode 58, easy] Length of Last Word
- 【Leetcode长征系列】Length of Last Word
- Lintcode422 Length of Last Word solution 题解
- LeetCode——Length of Last Word
- Leetcode 58 Length of Last Word
- [LeetCode] Length of Last Word
- Length of Last Word
- LeetCode-Length of Last Word
- Minimum Depth of Binary Tree & Length of Last Word & Trapping Rain Water
- LeetCode Length of Last Word
- LeetCode58:Length of Last Word
- Length of Last Word
- LeetCode Length of Last Word
- leetcode:Length of Last Word
- LeetCode——Length of Last Word
- LeetCode #58 Length of Last Word
- Length of Last Word
- Length of Last Word
- [LeetCode][Java] Length of Last Word