方法一:倒着找空格,并计算空格出现的个数。
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length(), index = -1, lastposition = len-1,cnt=0;
string sep = " ";
while(lastposition!=-1&&-1!=(index=s.find_last_of(sep,lastposition))){
if(index==lastposition){
lastposition--;
cnt++;
}
else{
return len-index-1-cnt;
}
}
if(lastposition==-1){
return 0;
}
return len-cnt;
}
};
方法二:顺着找,并及时擦除前面的字符串。
<pre name="code" class="cpp">class Solution {
public:
int lengthOfLastWord(string s) {
int len=0;
int pos;
while (s.length()!=0){
pos = s.find(" ");
if (pos==string::npos)
return s.length();
else{
if (pos!=0)
len = pos;
s.erase(0,pos+1);
}
}
return len;
}
};