leetcode-58-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.

For example,
Given s = “Hello World”,
return 5.

分析


求最后一个单词的字母数。如果不用 C++ 的 STL 的话,还是得将 string 转换为 c_str,也就是 char *,所以,试试纯粹的C?

解决方案1(C)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int lengthOfLastWord(char* s) {
if(!s) {
return 0;
}

int result = 0;
int slen = strlen(s);
while(s[slen-1] == ' ') {
slen--;
}
for(int i = slen-1; i>=0; i--) {
if(s[i] == ' ') {
break;
}
result++;
}
return result;
}

解决方案1(C++)


如果不用STL,可以将string 类型转换为C的c_str

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int lengthOfLastWord(string s) {
return lengthOfLastWord(s.c_str());
}
private:
int lengthOfLastWord(const char* s) {
if(!s) {
return 0;
}

int result = 0;
int slen = strlen(s);
while(s[slen-1] == ' ') {
slen--;
}
for(int i = slen-1; i>=0; i--) {
if(s[i] == ' ') {
break;
}
result++;
}
return result;
}
};

解决方案3(Python)


最简洁的还是Python

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
word_list = s.split(" ")
try:
last_word = word_list[-1]
return len(last_word)
except IndexError:
return 0

题目来源