728x90
반응형
Length of Last Word - LeetCode
Can you solve this real interview question? Length of Last Word - 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:
leetcode.com
문제
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.
풀이
나의 풀이법
풀이 접근 과정
그냥 “ “로 split한 뒤, 가장 뒤에 있는 글자의 개수만 리턴시키면 됐다.
만약 공백으로 찬 배열이면 없애버리고 !
아주 간단했던 문제.
최종 소스코드
class Solution {
fun lengthOfLastWord(s: String) = s.split(" ").filter { it != " " && it != "" }.last().length
}
728x90
반응형
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 141. Linked List Cycle (0) | 2023.08.27 |
---|---|
[LeetCode/Kotlin]Easy - 392. Is Subsequence (0) | 2023.07.07 |
[LeetCode/Kotlin]Easy - 1356. Sort Integers by The Number of 1 Bits (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 28. Find the Index of the First Occurrence in a String (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 219. Contains Duplicate II (0) | 2023.06.30 |