博客
关于我
leetcode 58. Length of Last Word
阅读量:108 次
发布时间: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/

你可能感兴趣的文章
mysql 数据库存储引擎怎么选择?快来看看性能测试吧
查看>>
MySQL 数据库操作指南:学习如何使用 Python 进行增删改查操作
查看>>
MySQL 数据库的高可用性分析
查看>>
MySQL 数据库设计总结
查看>>
Mysql 数据库重置ID排序
查看>>
Mysql 数据类型一日期
查看>>
MySQL 数据类型和属性
查看>>
mysql 敲错命令 想取消怎么办?
查看>>
Mysql 整形列的字节与存储范围
查看>>
mysql 断电数据损坏,无法启动
查看>>
MySQL 日期时间类型的选择
查看>>
Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
查看>>
MySQL 是如何加锁的?
查看>>
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>