Leetcode-058 – length of the last word

Time:2022-1-9

Length of the last word

Title Description: give you a string s, which consists of several words separated by spaces. Returns the length of the last word in a string. If the last word does not exist, return 0.

A word is the largest substring that consists of only letters and does not contain any space characters.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: use lastIndexOf method

First, usetrim()Method willsRemove the front and back spaces of, and then judge ifsWhether the contains spaces. If not, it indicates that there is only one word, which is returned directlysThe length of the; If yes, uselastIndexOf()Method acquisitionsThe position of the last space in thesubstring()Method interceptionsReturns the length of the last word in the.

public class LeetCode_058 {
    public static int lengthOfLastWord(String s) {
        s = s.trim();
        if (!s.contains(" ")) {
            return s.length();
        }
        int lastIndexOfSpace = s.lastIndexOf(" ");
        return s.substring(lastIndexOfSpace, s.length() - 1).length();
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLastWord("Hello World"));
    }
}

[daily message]If the other person doesn’t have a smile on his face, show his smile to ta. Face every day with a smile.

Recommended Today

Summary of import and export usage in JavaScript

import import 和 require 的区别 import 和js的发展历史息息相关,历史上 js没有模块(module)体系,无法将一个大程序拆分成互相依赖的小文件,再用简单的方法拼装起来。这对开发大型工程非常不方便。在 ES6 之前,社区制定了一些模块加载方案,最主要的有 CommonJS 和 AMD 两种。前者用于服务器,后者用于浏览器。ES6 在语言标准的层面上,实现了模块功能,而且实现得相当简单,完全可以取代 CommonJS 和 AMD 规范,成为浏览器和服务器通用的模块解决方案。也就是我们常见的 require 方法。 比如 `let { stat, exists, readFile } = require(‘fs’);` 。ES6 在语言标准的层面上,实现了模块功能。ES6 模块不是对象,而是通过export命令显式指定输出的代码,再通过import命令输入。 import 的几种用法: 1. import defaultName from ‘modules.js’; 2. import { export } from ‘modules’; 3. import { export as ex1 } from […]