美文网首页
LeetCode 58. Length of Last Word

LeetCode 58. Length of Last Word

作者: chengruru | 来源:发表于2018-08-10 10:56 被阅读0次
题目

       计算字符串(用空格分隔之后)最后一个单词长度。

Note:

        注意空串或者" 全是空格",这样特殊字符串的影响。

思路分析

    1. 去除字符串前后多余的空格: s.trim();
    2.使用split(" ")函数进行分割。

代码实现如下:

public int lengthOfLastWord(String s) {
        
        if(s.trim().equals(""))
            return 0;
        
        String[] strings = s.split(" ");
        return strings[strings.length - 1].length();

}

相关文章

网友评论

      本文标题:LeetCode 58. Length of Last Word

      本文链接:https://www.haomeiwen.com/subject/mplkbftx.html