Leetcode(58) Length of Last Word

Description

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:

1
2
Input: "Hello World"
Output: 5

解法

这题看似简单,其实坑挺多的。

比如:

1.最后一个字符为空格的情况

2.最后的字符连续为空格的情况

3.多个连续空格的情况

因为采用的方法为从后往前扫描,所以只要注意前2个坑就好啦~

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int lengthOfLastWord(String s) {
int res = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
if (res != 0) {
break;
} else {
continue;
}
}
res++;
}
return res;
}
}