난이도: EASY
문제 링크: https://leetcode.com/problems/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: 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.
나의 최종 제출 답안:
class Solution {
public int lengthOfLastWord(String s) {
// 앞뒤 공백 제거 후 연속된 공백을 하나로 처리
String[] words = s.trim().split("\\s+");
// 마지막 단어의 길이 반환
return words[words.length - 1].length();
}
}

코파일럿에게 더 간단하고 효율적이게 수정해달라고 요청한 답안:
split() 없이 직접 문자열을 뒤에서 탐색하며 마지막 단어의 길이를 구하기.
→ 불필요한 배열 생성 없이 O(n) 시간 복잡도로 해결
class Solution {
public int lengthOfLastWord(String s) {
int length = 0;
int i = s.length() - 1;
// 문자열 끝에서부터 공백 제거
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
// 마지막 단어의 길이 계산
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}
개선된 점:
- trim() 없이 직접 문자열 끝부터 공백을 제거하여 불필요한 메모리 사용을 줄임.
- split()을 사용하지 않고 문자 하나씩 탐색해 마지막 단어의 길이를 찾음.
- 배열을 생성하지 않아 메모리 사용이 줄어들고 실행 속도가 더 빠름.
이 방식은 공간 복잡도가 O(1)이고, 시간 복잡도도 O(n)이므로 더욱 효율적.
'Coding Challenges > LeetCode' 카테고리의 다른 글
| [Java] 35. Search Insert Position (2) | 2025.06.16 |
|---|---|
| [SQL50] 1251. Average Selling Price (0) | 2025.03.06 |
| [SQL50] 620. Not Boring Movies (0) | 2025.03.06 |
| [SQL50] 1729. Find Followers Count (0) | 2025.03.05 |
| [SQL50] 596. Classes More Than 5 Students (0) | 2025.03.05 |