728x90
Above is the link to the problem.
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:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
I solved this problem by writing the code below.
There is no need for exception handling in this problem because there is a condition that it has at least one word.
However, I wrote it to solve the problem in general.
Remove spaces before and after the string using the strip function, and output the length of the last word by separating it based on the space through the split function.
This code gets the top 19.92% of time efficiency and the top 60.38% of space efficiency.
728x90
반응형
'Code > LeetCode' 카테고리의 다른 글
[LeetCode] 70. Climbing Stairs (Easy/Python) (0) | 2022.09.15 |
---|---|
[LeetCode] 67. Add Binary (Easy/Python) (0) | 2022.09.08 |
[LeetCode] 48. Rotate Image (Medium/Python) (0) | 2022.09.05 |
[LeetCode] 35. Search Insert Position (Easy/Python) (0) | 2022.09.03 |
[LeetCode] 20.Valid Parentheses (Easy/Python) (0) | 2022.09.02 |