博客
关于我
leetcode 58. Length of Last Word
阅读量:109 次
发布时间:2019-02-26

本文共 983 字,大约阅读时间需要 3 分钟。

一 题目

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.

Example:

Input: "Hello World"Output: 5

二 分析

easy 级别。求字符串包含空格分割后的最后一个子串的长度。

字符串的题目,这个我理解就是单纯的api使用,没啥算法了,从头遍历。有些边界case要注意,比如"a ",还有尾部没有空格" a"。

还有全是空格的“         ”。所以要trim()处理。这里使用了数组来处理。

public static int lengthOfLastWord(String s) {				if(s== null || s.length()==0){			return 0;		}		String[] arrays= s.split(" ");		        String str =arrays[arrays.length-1];                return str.length();    }

Runtime: 1 ms, faster than 46.94% of Java online submissions for Length of Last Word.

Memory Usage: 35.6 MB, less than 100.00% of Java online submissions forLength of Last Word.

看了下讨论区,还有大神一行代码直接算。用trim 之后总长度-最后一次“”的位置。

    public static int lengthOfLastWord(String s) {
     return s.trim().length()-s.trim().lastIndexOf(" ")-1;
    }

 

转载地址:http://srdy.baihongyu.com/

你可能感兴趣的文章
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>
os.removexattr 的 Python 文档——‘*‘(星号)参数是什么意思?
查看>>
os.system 在 Python 中不起作用
查看>>
OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
查看>>
OSCACHE介绍
查看>>
SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
查看>>
OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
查看>>
SQL--mysql索引
查看>>
OSChina 周四乱弹 ——程序员为啥要买苹果手机啊?
查看>>
OSChina 周日乱弹 —— 2014 年各种奇葩评论集合
查看>>
OSChina 技术周刊第十期,每周技术抢先看!
查看>>
oscp--python
查看>>
OSError: no library called “cairo-2“ was foundno library called “cairo“ was foundno library called
查看>>
OSError: [WinError 193] %1 不是有效的 Win32 应用程序。
查看>>
osgearth介绍
查看>>
OSGi与Maven、Eclipse PlugIn的区别
查看>>
Osgi环境配置
查看>>
OSG——选取和拖拽
查看>>
OSG中找到特定节点的方法(转)
查看>>
OSG学习:C#调用非托管C++方法——C++/CLI
查看>>