leetcode解题: Length of Last Word (58)

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.

解法1:

这题的启发,也用istringstream来读取一个个的word,直到最后一个string。
C++
```
这里要注意的是, getline会读取word直到下一个delimiter的出现,那么如果有两个连续的space,第二个space之前会读出一个“”, 也就是空字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int lengthOfLastWord(string s) {
istringstream ss(s);
string word;
int res = 0;
while (getline(ss, word, ' ')) {
if (!word.empty()) {
res = word.size();
}
}
return res;
}
};

Java

1

解法2:

不用istringstream的操作, 一位位的读。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int lengthOfLastWord(string s) {
int res = 0;
int count = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == ' ') {
if (count != 0) {
res = count;
}
count = 0;
} else {
++count;
}
}
if (count) res = count;
return res;
}
};