鱼C论坛

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

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

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

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

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

x
  1. Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

  2. If the last word does not exist, return 0.

  3. Note: A word is defined as a character sequence consists of non-space characters only.

  4. Example:

  5. Input: "Hello World"
  6. Output: 5
复制代码

  1. class Solution {
  2.     public int lengthOfLastWord(String s) {
  3.         
  4.         s = s.replaceAll(" +"," ");
  5.         
  6.         if(s.equals(" ")){
  7.             
  8.             return 0;
  9.         }
  10.         
  11.         String[] result = s.split(" ");
  12.         
  13.         return result[result.length-1].length();
  14.         
  15.     }
  16. }
复制代码


16.jpg

利用split方法,效率有点低,继续改进。

  1. class Solution {
  2.     public int lengthOfLastWord(String s) {
  3.         
  4.         s = s.trim();
  5.         
  6.         return s.length() - (s.lastIndexOf(" ") +1) ;
  7.     }
  8. }
复制代码


17.jpg

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-27 05:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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