Leetcode58. Length of Last Word
Posted 于淼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode58. 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不合适。
以上是关于Leetcode58. Length of Last Word的主要内容,如果未能解决你的问题,请参考以下文章
一天一道LeetCode#58. Length of Last Word
Java [Leetcode 58]Length of Last Word
[LeetCode]58. Length of Last Word
Leetcode58 Length of Last Word