DEV Community

Cover image for Length of Last Word
FakeStandard
FakeStandard

Posted on • Edited on

Length of Last Word

#58.Length of Last Word

Problem statement

Given a string s consisting of words and spaces, return the length of the last word in the string.

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

Example 1

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

Example 2

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

Example 3

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

Explanation

給定一個由單字和空格組成的字串 s ,返回字串中最後一個單字的長度

Solution

題目淺顯易懂,解題方式也不難,在不講求效能的前提下,直接使用 C# 內建方法來解

先用 Trim() 將頭尾空白去除,緊接著用 Split() 將字串分割為陣列,分割基準為空白,得到陣列後直接返回最後一個索引位置的元素長度,由於不知道分割後的陣列大小,用 Length 屬性取得其長度,因為陣列索引是由 0 開始,故取得長度後再減去 1 就是最後一個元素的索引

public int LengthOfLastWord(string s)
{
    string[] words = s.Trim().Split(' ');

    return words[words.Length - 1].Length;
}
Enter fullscreen mode Exit fullscreen mode

Reference

LeetCode Solution

GitHub Repository


Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution
or follow my GitHub ⭐ I'd appreciate it.


Top comments (0)