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
.
思路:计算最后一位字符串的长度。通过split()方法把整个字符串转为List,若List长度大于等于1,计算String长度;若List长度小于1,返回0。
代码如下:
import java.util.Arrays;
import java.util.List;
/**
* Created by Poldi on 2017/7/20.
*/
public class LengthOfLastWord {
public int lengthOfLastWord(String s) {
List<String> list = Arrays.asList(s.split(" +"));
int length = 0;
if (list.size()<1){
length = 0;
}else {
String last = list.get(list.size()-1);
length = last.length();
}
return length;
}
public static void main(String[] args) {
LengthOfLastWord lengthOfLastWord = new LengthOfLastWord();
System.out.println(lengthOfLastWord.lengthOfLastWord("Hello World"));
}
}
Runtime: 11 ms