一.问题描述
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 len = s.length();
if(len==0) return 0;
int i= len-1;
while(s[i]==' ' && i>=0)
i--;
if(i<0) return 0;
int end=i;
while(s[i]!=' ' && i>=0)
i--;
int st=i+1;
int res = end -st+1;
return res;
}
};