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.
주어진 문자열에서 가장 마지막 단어의 길이를 구하는 문제로 주어진 문자열을 reversed로 뒤집은 후 strip으로 좌우 공백을 제거한다.
그 후 " "를 찾은 후 해당 위치를 반환한다면 그 길이가 되는 것을 알 수 있다.
class Solution:
def lengthOfLastWord(self, s: 'str') -> 'int':
str = ''.join(reversed(s)).strip()
if str.find(" ") < 0:
return len(str)
else:
return str.find(" ")
문제 출처 : https://leetcode.com/problems/length-of-last-word/
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
Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_58.py
GitHub - kkkkang1009/leetcode: leetcode
leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.
github.com
'IT > LeetCode' 카테고리의 다른 글
[LeetCode] 63. Unique Paths II (0) | 2022.08.17 |
---|---|
[LeetCode] 62. Unique Paths (0) | 2022.08.17 |
[LeetCode] 53. Maximum Subarray (0) | 2022.08.15 |
[LeetCode] 38. Count and Say (0) | 2022.07.22 |
[LeetCode] 35. Search Insert Position (0) | 2022.07.22 |
댓글