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.
思路:注意细节即可。
class Solution {
public:
int lengthOfLastWord(string s) {
int temp = 0;
int result = 0;
if(s.empty()) return 0;
int n = s.length();
for(int i=0;i<n;i++){
if(s[i]!=' ') temp++;
//此处注意,如果不增加s[i-1]!=' '这个条件
//出现连续空格时,result = temp会多次执行,导致result被0覆盖
//增加此条件可以确保result = temp只执行一次
if(s[i]==' ' && s[i-1]!=' '){
result = temp;
temp = 0;
}
}
//如果字符串不以空格结尾,则for循环结束时,temp还未赋值给result
//故直接返回temp
if(s[n-1]!=' ') return temp;
//否则返回result
else return result;
}
};