물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

58. Length of Last Word

BEstyle 2022. 12. 27. 18:40

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

A 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.

Example 2:

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

Example 3:

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

 

Constraints:

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

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.rstrip().split(" ")[-1])

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

49. Group Anagrams  (0) 2022.12.27
14. Longest Common Prefix  (0) 2022.12.27
1299. Replace Elements with Greatest Element on Right Side  (0) 2022.12.27
242. Valid Anagram  (0) 2022.12.27
345. Reverse Vowels of a String  (0) 2022.12.27