Length of Last Word–LeetCode#58

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

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部