【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:---------9ms

 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不合适。

改:(若不使用lastindexof这个已有的函数 手写方法如下)---------10ms

public int lengthOfLastWord(String s) {
        if ((s == "") || (s == " "))
            return 0;
        s = s.trim();
        // 手写lastindex
        int ans = 0;
        System.out.println(s.length());
        for (int i = s.length(); i > 0; i--) {
            char zimu = s.charAt(i - 1);
            if (zimu == ' ')
                break;
            else {
                ans++;
            }
        }
        System.out.println(ans);
        return ans;
    }

当不使用trim的时候:---------12ms

public int lengthOfLastWord(String s) {
        if ((s == "") || (s == " "))
            return 0;
        //s = s.trim();
       
        // 手写lastindex
        int ans = 0;
        int leng=0;
      //去掉string末尾的空格 但是不使用trim 先对空格进行计数 lengzimu
for (int i = s.length(); i > 0; i--) { char lengzimu = s.charAt(i - 1); if (lengzimu == ' '){ leng++; } if(lengzimu!=' ')break; } int k=s.length()-leng; System.out.println(k);
      //从去掉空格的位置开始倒便利
for(int i=k;i>0;i--){ char zimu = s.charAt(i - 1); if (zimu != ' '){ ans++; } if(zimu==' ') break; } System.out.println(ans); return ans; }
原文地址:https://www.cnblogs.com/yumiaomiao/p/7110434.html