鱼C论坛

 找回密码
 立即注册
查看: 1748|回复: 0

[学习笔记] leetcode 58. Length of Last Word

[复制链接]
发表于 2019-8-20 06:24:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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
class Solution {
    public int lengthOfLastWord(String s) {
        
        s = s.replaceAll(" +"," ");
        
        if(s.equals(" ")){
            
            return 0;
        }
        
        String[] result = s.split(" ");
        
        return result[result.length-1].length();
        
    }
}

16.jpg

利用split方法,效率有点低,继续改进。
class Solution {
    public int lengthOfLastWord(String s) {
        
        s = s.trim();
        
        return s.length() - (s.lastIndexOf(" ") +1) ;
    }
}

17.jpg

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 00:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表