WebJun 9, 2024 · If the length of the list is not empty, we will return the last word length. To access the last element of a Python list we can use index -1. Let’s see the full code below. class Solution: def lengthOfLastWord(self, s: str) -> int: str_arr = s.split() if len(str_arr) == 0: return 0 else: return len(str_arr[-1]) WebJul 12, 2024 · class Solution: def lengthOfLastWord (self, s: str) -> int: if not s: return 0 wordlist = s.split () # strip ()可以删除开头和结尾的空格 # split ()分割字符串 return len (wordlist [-1]) 这样会在输入是‘ ’发生错误,此时的wordlist里面没有参数。 这句如果改成wordlist = s.split (' ') 当输入为‘a ’,a之后有空格,那么wordlist [-1]是一个空字符串,长度 …
What is the purpose of using " -> int" after a function def …
WebMay 6, 2024 · class Solution: def lengthOfLastWord(self, s: str) -> int: return len(s.strip(' ').split(' ')[-1]) WebFeb 21, 2024 · class Solution: def lengthOfLastWord(self, s: str) -> int: if(s == " "): return 0 res = s.split(" ") for i in range(len(res) - 1, -1, -1): if(res[i] != ''): return len(res[i]) return 0 easy trifle bowl desserts
Leetcode(Python) Mark He - GitHub Pages
Webclass Solution: def getPermutation (self, n: int, k: int)-> str: st = [False] * 10 res = '' for i in range (n): # 枚举每一个位置 fact = 1 # 计算出剩余的选法: (n-i)! for j in range (1, n-i): fact = fact * j # 遍历所有数字 for j in range (1, n + 1): if st [j]: # 没有用过的数字 continue if fact < k: #如果没有到k ... WebFeb 3, 2024 · In this code I have use split () function by which i converted the string into the list elements and then calculated the last word length i.e. class Solution: def … Web"class Solution: def lengthOfLastWord(self, s: str) -> int: """ 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. easy trifle recipe uk