LeetCode No.58 Length of Last Word | #String

Q:

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.
For example, Given s = "Hello World" ,return 5

A:

以“Hello[space]World[space][space]”为例:
第一个while先判断出了这里有两个空格,length of str缩减了两个,现在对s.charAt(index)来说已经指向了字母“d”,判断 s.charAt(len-1) != ' ',累加lastLength,然后length of str继续缩减,直到指向了第一个[space],第二个while也结束了,返回lastLength结果。

public int lengthOfLastWord(String s) {
    int len=s.length(), lastLength=0;
    
    while(len > 0 && s.charAt(len-1)==' '){ //处理字符串结尾还有空格的情况
        len--;
    }
    
    while(len > 0 && s.charAt(len-1)!=' '){
        lastLength++;
        len--;
    }
    
    return lastLength;
}
```
----

>**java.lang.String.charAt() **方法返回指定索引处的char值。索引范围是从0到length() - 1。
声明: `public char charAt (int index)`
此方法返回这个字符串的指定索引处的char值。第一个char值的索引为0.
**IndexOutOfBoundsException** -- 如果index参数为负或不小于该字符串的长度.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 题目 原题链接:A. Again Twenty Five! 题意 输入一个n,求5的n次方的最后两位。除了1以外,...
    ss5smi阅读 137评论 0 0
  • 文/六壹 (一) 开启了一扇新的门, 不知道门里是什么。 开启了一页新的篇章, 不知道剧情会如何发展。 (二) 你...
    栗子六壹阅读 693评论 0 51
  • 苏州的姑苏区就是街沿河,河连着桥,两岸白墙青瓦,一户户人家,琳琅满目的现代商铺,兜售古老的民族特色商品、特色小吃、...
    九宫格格阅读 183评论 0 0