知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 58. Length of Last Word (Easy/Python)

코방코 2022. 9. 7. 07:23
728x90
 

Length of Last Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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
반응형