Code & Func
2017-12-12

第76天。

快考试,可能要水一个月的easy题了。

今天的题目是Length of Last Word:

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

一看完题目,我就想到了pythonsplit:

1
def lengthOfLastWord(self, s):
2
"""
3
:type s: str
4
:rtype: int
5
"""
6
words = s.split();
7
if len(words) == 0: return 0;
8
return len(words[-1])

然后是用c++find去解的:

1
int lengthOfLastWord(string s) {
2
auto beg = s.begin();
3
auto it = beg;
4
auto end = s.end();
5
// fix the bug like that "hello world "
6
for(int i = s.size() - 1;i >= 0 && s[i] == ' ';i--)
7
end--;
8
9
while((it = find(beg,end,' ')) != end) {
10
beg = it + 1;
11
}
12
return end - beg;
13
}

然后是从后面向前扫描的方法:

1
int lengthOfLastWord(string s) {
2
auto end = s.rbegin();
3
while(end != s.rend() && *end == ' ') end++;
4
auto beg = end;
5
while(beg != s.rend() && *beg != ' ') beg++;
6
return beg - end;
7
}

然后是dicuss中的解法,和上面的从后向前扫描的方法类似,只不过它第二个循环里面顺带计算了length:

1
int lengthOfLastWord(string s) {
2
int len = 0, tail = s.length() - 1;
3
while (tail >= 0 && s[tail] == ' ') tail--;
4
while (tail >= 0 && s[tail] != ' ') {
5
len++;
6
tail--;
7
}
8
return len;
9
}
上一条动态