iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0
自我挑戰組

30天 Leetcode解題之路系列 第 12

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 11 - Roman to Integer
下一篇
Day 13 - Add Binary
系列文
30天 Leetcode解題之路30

尚未有邦友留言

立即登入留言