博客
关于我
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/

你可能感兴趣的文章
SpringBoot中集成eclipse.paho.client.mqttv3实现mqtt客户端并支持断线重连、线程池高并发改造、存储入库mqsql和redis示例业务流程,附资源下载
查看>>
Padding
查看>>
paddlehub安装及对口罩检测
查看>>
SpringBoot中集成Actuator实现监控系统运行状态
查看>>
PaddleSlim 模型量化 源代码解读
查看>>
paddle的两阶段基础算法基础
查看>>
Page Object模式:为什么它是Web自动化测试的必备工具
查看>>
SpringBoot中重写addCorsMapping解决跨域以及提示list them explicitly or consider using “allowedOriginPatterns“ in
查看>>
PageHelper 解析及实现原理
查看>>
pageHelper分页工具的使用
查看>>
pageHelper分页技术
查看>>
PageHelper分页查询遇到的小问题
查看>>
PageHelper实现分页详细版、整合SSM应用
查看>>
PageHelper常见问题
查看>>
SpringBoot中配置为开发模式,代码修改后不用重新运行
查看>>
springboot中pom.xml、application.yml、application.properties
查看>>
PageHelper:上手教程(最详细)
查看>>
PageOffice如何实现从零开始动态生成图文并茂的Word文档
查看>>
PageRank算法
查看>>
Paint类(画笔)
查看>>