Post

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