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

你可能感兴趣的文章
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>
mysqldump的一些用法
查看>>
mysqli
查看>>
MySQLIntegrityConstraintViolationException异常处理
查看>>
mysqlreport分析工具详解
查看>>
MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
查看>>
Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
查看>>