Description:
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.
Example:
Input: "Hello World" Output: 5
这个问题还是挺简单的,代码如下:
class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0;
int i = s.size()-1;
while(i>=0){
if(s[i]==' ')
count = 0;
else if(s[i]!=' ' && i==0)
return count+=1;
else if(s[i]!=' ' && s[i-1]==' ')
return count+=1;
else
count++;
i--;
}
return count;
}
};
注意一下几个问题:
i++ :先引用后增加
++i :先增加后引用
i++ :先在i所在的表达式中使用i的当前值,后让i加1
++i :让i先加1,然后在i所在的表达式中使用i的新值