​LeetCode刷题实战58:最后一个单词的长度

程序IT圈

共 1486字,需浏览 3分钟

 · 2020-10-06

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 最后一个单词的长度,我们先来看题面:

https://leetcode-cn.com/problems/length-of-last-word/

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.


If the last word does not exist, return 0.


Note: A word is defined as a maximal substring consisting of non-space characters only.


题意

给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。

样例

输入: "Hello World"
输出: 5


解题


这道题属于比较简单的算法题了。首先判空,字符串为0的情况。

从后向前遍历字符串的每个字符,使用s.charAt(i),如果不等于空就计数;如果为空,并且计数不是0,就说明最后的单词已经记完数了,可以返回了。


class Solution {
    public int lengthOfLastWord(String s) {
        if(s==null || s.length()==0)
            return 0;
        int len = s.length();
        int count = 0;
        for(int i=len-1;i>=0;i--){
            if(s.charAt(i)!=' '){
                count++;
            }else if(s.charAt(i)==' '&& count!=0){
                return count;
            }
        }
        return count;
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。


上期推文:


LeetCode1-50题汇总,速度收藏!
LeetCode刷题实战51:N 皇后
LeetCode刷题实战52:N皇后 II
LeetCode刷题实战53:最大子序和
LeetCode刷题实战54:螺旋矩阵
LeetCode刷题实战55:跳跃游戏
LeetCode刷题实战56:合并区间
LeetCode刷题实战57:插入区间


浏览 29
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报