资讯专栏INFORMATION COLUMN

[Leetcode] Length of Last Word 最后一个单词长度

happen / 656人阅读

摘要:代码双指针法复杂度时间空间思路从后往前看字符串,跳过所有空格后,记下该结束位置,再到下一个空格,再记录一个开始位置,则长度就是结束位置减去开始位置。

Length of Last Word

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

API法 复杂度

时间 O(N) 空间 O(N)

思路

简单的使用API。先trim再split再用length。

代码
public class Solution {
    public int lengthOfLastWord(String s) {
        return s.trim().split(" +")[s.trim().split(" +").length - 1].length();
    }
}
双指针法 复杂度

时间 O(N) 空间 O(1)

思路

从后往前看字符串,跳过所有空格后,记下该结束位置,再到下一个空格,再记录一个开始位置,则长度就是结束位置减去开始位置。在跳过空格的循环后,要判断是否已经超界,如果超界则返回0

代码
public class Solution {
    public int lengthOfLastWord(String s) {
        int idx = s.length() - 1;
        // 跳过末尾的空格
        while(idx >= 0){
            if(s.charAt(idx) != " ") break;
            idx--;
        }
        // 记录结束位置
        int end = idx;
        // 如果已经超界返回0
        if(idx < 0) return 0;
        // 找到开始位置
        while(idx >= 0){
            if(s.charAt(idx) == " ") break;
            idx--;
        }
        return end - idx;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64694.html

相关文章

  • leetcode _58 length of the last word

    摘要:问题很简单,就是给你一个字符串,你求出这个字符串中所包含的最后一个单词的长度虽然问题很简单,但是最开始的方向不对,其实整个问题可以直接通过数字来解决而字符串中的单词内容并没有什么关系先求出去掉首位空格后,找到最后一次出现空格即出现最后一个词 问题很简单,就是给你一个字符串,你求出这个字符串中所包含的最后一个单词的长度 虽然问题很简单,但是最开始的方向不对,其实整个问题可以直接通过数字来...

    Darkgel 评论0 收藏0
  • [Leetcode] Word Break 单词分解

    摘要:所以只要验证满足这个条件,我们则可以确定这个较长的字符串也是可分解的。同时,我们用数组记录下字符串长度递增时可分解的情况,以供之后使用,避免重复计算。当遍历完这个词典并找出所有以第一个字母开头的词以后,我们进入下一轮搜索。 Word Break I Given a string s and a dictionary of words dict, determine if s can ...

    Ververica 评论0 收藏0
  • [Leetcode] Substring with Concatenation of All Wor

    摘要:每次搜索中,我们通过哈希表维护一个窗口,比如中,我们先拿出。如果都不在数组中,那说明根本不能拼进去,则哈希表全部清零,从下一个词开始重新匹配。 Substring with Concatenation of All Words You are given a string, s, and a list of words, words, that are all of the same...

    adie 评论0 收藏0
  • leetcode318. Maximum Product of Word Lengths

    摘要:将低位的二进制数分别对应字母,从而用二进制数实现一个简单的。因此单词对应的二进制数为那么比较两个单词是否有重复的字母只需要将二者的二进制形式进行操作即可。 题目要求 Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do ...

    Moxmi 评论0 收藏0
  • [Leetcode] Word Search I&II 二维字符矩阵查找单词

    摘要:复杂度时间空间为长度,为大小空间复杂度是是因为我用存信息,只动态地存当前的路径如果用来存信息的话空间复杂度就是时间复杂度对每个点都要作为起始点,对于每个起始点,拓展一次有四个可能性四个邻居,要拓展次长度为。思路暴力搜索带走。 Word Search I Given a 2D board and a word, find if the word exists in the grid. ...

    LuDongWei 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<