š” 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.