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
.
已AC,代码如下,一开始几个没想到,调试了十多分钟。。。。
<span style="font-size:18px;">class Solution {
public:
int lengthOfLastWord(const char *s) {
string str(s);
int beg =0, end = str.size()-1;
int index = -1;
//for(int i = beg; i <= end ;i++) //去掉开头的空格
// if(str[i] == ' ') beg++;
//else break;
for(int i = end; i >= 0; i--) //去掉尾部的空格
if(str[i] == ' ') end--;
else break;
str = str.substr(beg,end-beg+1);
int i =0;
while(str[i] != '\0')
{
if(str[i++] == ' ')
index = i;
}
if(index == -1)
{
return str.size();
}
else
{
return str.size()-index;
}
}
};</span>