[LeetCode] Length of Last Word
2013-11-08 14:00
447 查看
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
问题描述:给定一个字符串,它包含空格,返回这个字符串中最后一个单词的长度。
如果没有最后一个单词,则返回0,这里“没有最后一个单词”理解为没有单词。
由于参数给定的类型是const char *,因此,这题考察的是指针的操作。
用参数给定的s字符指针来遍历字符串,用一个int型整数来记录长度,当遍历的字符没有结束,也就是*s != 0时,就判断该字符是否为' '字符,如果是空格,就继续遍历把空格略去,当然在去掉空格的过程中,同样要判断是否还有字符,如果在这儿就没有字符了,就返回之前得到的单词的长度,如果后面还有字符,那么就需要将长度计数置为0,遍历完成后,返回长度。
' ', 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.
问题描述:给定一个字符串,它包含空格,返回这个字符串中最后一个单词的长度。
如果没有最后一个单词,则返回0,这里“没有最后一个单词”理解为没有单词。
由于参数给定的类型是const char *,因此,这题考察的是指针的操作。
用参数给定的s字符指针来遍历字符串,用一个int型整数来记录长度,当遍历的字符没有结束,也就是*s != 0时,就判断该字符是否为' '字符,如果是空格,就继续遍历把空格略去,当然在去掉空格的过程中,同样要判断是否还有字符,如果在这儿就没有字符了,就返回之前得到的单词的长度,如果后面还有字符,那么就需要将长度计数置为0,遍历完成后,返回长度。
class Solution { public: int lengthOfLastWord(const char *s) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int len = 0; while(*s) { if(*s == ' ') { while(*s && *s == ' ') ++s; if(*s == 0) return len; len = 0; } ++len; ++s; } return len; } };
相关文章推荐
- [LeetCode] Length of Last Word
- Leetcode_Length of Last Word
- LEETCODE-Length of Last Word
- 【leetcode Java】Length of Last Word
- LEETCODE: Length of Last Word
- LeetCode Length of Last Word
- [Leetcode]Length of Last Word
- LeetCode | Length of Last Word
- [leetcode] Length of Last Word
- LeetCode_Length Of Last Word
- Leetcode: Length of Last Word
- [LeetCode] Length of Last Word
- leetcode第一刷_Length of Last Word
- Leetcode Length of Last Word
- LeetCode 058 Length of Last Word
- Leetcode 58 Length of Last Word
- Length of Last Word -- LeetCode
- Java [Leetcode 58]Length of Last Word
- [leetcode] Length of Last Word
- LeetCode - Length of Last Word