💡 LeetCode 58 - Length of Last Word
💡 LeetCode 58 - 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.
입출력 예제
✅ 예제 1
1
2
3
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
✅ 예제 2
1
2
3
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
✅ 예제 3
1
2
3
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
제약조건
1 <= s.length <= 104
- s consists of only English letters and spaces ’ ’.
- There will be at least one word in s.
작성 코드
1
2
3
4
5
6
7
8
9
10
class Solution {
public int lengthOfLastWord(String s) {
// 1. 변수 선언 및 초기화
String[] wordArr = s.split(" ");
String lastWord = wordArr[wordArr.length - 1];
// 2. 반환
return lastWord.length();
}
}
This post is licensed under CC BY 4.0 by the author.