leetcode [#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.

Example
Given s = “Hello World”,
return 5.

Note
A word is defined as a character sequence consists of non-space characters only.


解决方案

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0) return 0;
String[] arr = s.split(" ");
if(arr.length == 0){
return 0;
} else {
return arr[arr.length - 1].length();
}
}
}

注意事项

  1. 先处理特殊情况。
  2. 对字符串按空格切分,得到的数组如果长度为0,说明本来就是一系列空格组成的字符串,返回0;否则,返回数组最后一个元素的长度即可。