Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발자도전

[LeetCode] 58. Length of Last Word 본문

LeetCode

[LeetCode] 58. Length of Last Word

도do 2023. 2. 2. 15:21
728x90

[문제]

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.

 

주어진 문자열 s의 맨 마지막 단어의 길이를 return 시켜라.

 

[입출력 예]

 

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.

 

[답]

앞 뒤로 공백이 있을 경우 단어의 길이를 샐 수 없어서 trim 함수를 사용해서 공백을 제거해주었다.

문자열 s의 길이만큼 for문을 거꾸로 돌렸다.

만약 s의 i번째 값이 " "공백이 아니라면 count 값을 하나씩 더해줄 수 있도록 해주고 return 시켜주었다.

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 66. Plus One  (0) 2023.02.06
[LeetCode] 20. Valid Parentheses  (0) 2023.02.03
[LeetCode] 35. Search Insert Position - java  (0) 2023.02.01
[LeetCode] Valid Mountain Array  (0) 2023.01.31
[LeetCode] Check If N and Its Double Exist  (0) 2023.01.28
Comments