首页 > 代码库 > 【Leetcode】58. Length of Last Word

【Leetcode】58. Length of Last Word

Question:

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.

Leetcode submission:

 public int lengthOfLastWord(String s) {
        if((s=="")||(s==" ")) return 0;
            s=s.trim();
            System.out.println(s.length());
            int BlankIndex=s.lastIndexOf(" ")+1;//从0开始
            int ans=s.length()-BlankIndex;
            System.out.println(ans);
            return ans;
    }

完整可运行代码:

public class L58 {
    public int lengthOfLastWord(String s) {
         if((s=="")||(s==" ")) return 0;
            s=s.trim();
            System.out.println(s.length());
            int BlankIndex=s.lastIndexOf(" ")+1;//从0开始
            int ans=s.length()-BlankIndex;
            System.out.println(ans);
            return ans;
    }
    public static void main(String[] args) {
        L58 l58 = new L58();
        String s= "Hello  Wolll ";
        l58.lengthOfLastWord(s);
    }
}

 

注:

①trim()去除字符串收尾的空格 String s=s.trim()

②lastIndexOf() 返回最后一次出现的“ ”所在位置索引 从0开始计数

③开始用的split截取

String[] temp = s.split(" ");
int index=temp.length;
String last=temp[index-1];
ans=last.length();
 return ans;

但是split截取 只能使用一种规格截取比如一个空格或者两个空格,题目要求不管几个几个空格 都算一个分隔,所以split不合适。

【Leetcode】58. Length of Last Word