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
.
我的方法是:
- 先消除字符串首、尾的空格;
- 再从字符串尾向首查找,直到找到空格或者指针到队首都没找到空格为止,返回最后一个 word 的长度.
我方法,我代码:
\(O(n)\) time, \(O(1)\) extra space.
// 解题关键:消除 s 的首尾空格
int lengthOfLastWord(string s) {
const int n = s.size() - 1;
if (s.size() == 0) return 0;
int begin = 0, end = n;
//消除字符串首尾空格
if (s[0] == ' ') {
for (int i = 0; i < s.size(); i++) {
if (s[i] != ' ') {
begin = i;
break;
}
}
}
if (s[n] == ' ') {
for (int i = n; i >= 0; i--) {
if (s[i] != ' ') {
end = i;
break;
}
}
}
// 从尾部开始查找
for (int i = end; i >= begin; i--) {
if (s[i] == ' ') return end - i;
else if (i == begin) return end - begin + 1;
}
}