Leetcode 58 Length of Last Word

来源:互联网 发布:平面设计网络兼职 编辑:程序博客网 时间:2024/05/16 09:42

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.

我是用一种分开的办法

public class Solution {    public int lengthOfLastWord(String s) {        String[] str = s.split(" ");        if(str.length == 0) return 0;        return str[str.length-1].length();    }}
然后这是一种更简单的方法

public int lengthOfLastWord(String s) {    return s.trim().length()-s.trim().lastIndexOf(" ")-1;//trim()用来去掉字符串对象开头和结尾的空格 lastIndexOf用来返回后面指定字符串最后出现的位置}


0 0
原创粉丝点击