Day 12 - Length of Last Word

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题Day~


58. Length of Last Word

Question

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.


Example

Example1

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example2

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example3

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

解题

题目

首先先简单的翻译一下题目
给一个字串,其中组成的字会由数量不一的空白隔开,回传最後一个的字的长度。

Think

作法大致上是这样

  • 很简单,就切割字串,然後找到最後一个字,再回传他的长度。
  • Python的话,先用strip()去除原始字串前後的空白去掉,再用split()以空白切割字串,会存在list_s中,最後index可以用-1找到最後一个字,再回传长度就好。

Code

Python

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        list_s = s.strip().split(" ")
        # print(list_s)
        return len(list_s[-1])

C

int lengthOfLastWord(char * s){
    char *token;
    char *last_word;
    token = strtok(s, " ");

    while( token != NULL ) {
        // printf("%s\n", token);
        last_word = token;
        // printf("%s\n", last_word);
        token = strtok(NULL, " ");
        if (token == NULL){
            return strlen(last_word);
        }
    }

    return 1;
}

Result

  • Python

  • C

大家明天见/images/emoticon/emoticon29.gif


<<:  Day 12 MSW实战

>>:  【Day 12】Google Apps Script - API 篇 - Drive Service - 云端硬碟服务介绍

【程序】Onboarding process 转生成恶役菜鸟工程师避免 Bad End 的 30 件事 - 21

Onboarding process 第一周有哪些重点 每个月定期追踪 第三个月是最危险的 ...

自动化测试,让你上班拥有一杯咖啡的时间 | Day 24 - 学习 trigger 的用法

此系列文章会同步发文到个人部落格,有兴趣的读者可以前往观看喔。 今天要跟大家分享当网页上有子表时,...

Day2React安装方式简介

安装方式 根据官网介绍,本次铁人赛会着重介绍下列三种安装方式: CDN连结 快速建立react环境的...

【Day 30】终局之战!是什麽理由支撑我完成 30 天的铁人赛?

糖豆人过关~~ by 在游戏里真人大闯关?嘴上无聊身体真香的《糖豆人》 首先,庆祝完赛啦!!!ヽ(...

Day 24-Unit Test 应用於 ORM (以 Entity Framework 为例) (情境及应用-4)

Unit Test 应用於 ORM (以 Entity Framework 为例) - LINQ 介...