[LintCode] Length of Last Word 求末尾单词的长度

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.

Notice

A word is defined as a character sequence consists of non-space characters only.

Have you met this question in a real interview?
 
 
Example

Given s = "Hello World", return 5.

LeetCode上的原题,请参见我之前的博客Length of Last Word

解法一:

class Solution {
public:
/**
* @param s A string
* @return the length of last word
*/
int lengthOfLastWord(string& s) {
if (s.empty()) return ;
int res = ;
if (s[] != ' ') res = ;
for (int i = ; i < s.size(); ++i) {
if (s[i] != ' ') {
if (s[i - ] == ' ') res = ;
else ++res;
}
}
return res;
}
};

解法二:

class Solution {
public:
/**
* @param s A string
* @return the length of last word
*/
int lengthOfLastWord(string& s) {
int tail = s.size() - , res = ;
while (tail >= && s[tail] == ' ') --tail;
while (tail >= && s[tail] != ' ' ) {
--tail;
++res;
}
return res;
}
};
上一篇:java异常体系结构详解


下一篇:Java&Selenium控制滚动条方法封装