L58: 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.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = “Hello World”,
return 5.
解题思路:遇到非’ ‘字符,用一个符号表示word开始,遇到’ ‘表示word结束,注意边界情况处理
优化:可以从字符串末尾开始处理
class Solution {
public:
int lengthOfLastWord(string s) {
int strLen = s.length();
if(strLen == 0)
return 0;
int begin = 0;
int end = 0;
int pos = 0;
bool word_start = false;
while(pos < strLen)
{
if(s[pos] != ‘ ‘ && !word_start)
{
begin = pos;
word_start = true;
}
else if(s[pos] == ‘ ‘ && word_start)
{
end = pos;
word_start = false;
}
pos++;
}
if (word_start && pos == strLen)
end = strLen;
return end - begin;
}
};
Leetcode题解(5):L58/Length of Last Word
原文地址:http://blog.csdn.net/kzq_qmi/article/details/46413719