Capitalize String
Capitalize String - Explanation
Problem Summary
Write a function that capitalizes the first letter of a string.
Go to Problem →Detailed Explanation
이 문제는 **문자열 분리**와 **대소문자 변환**을 결합하여 첫 글자만 대문자로 만드는 방법을 학습합니다. **핵심 전략: 분리 후 결합** 1. 첫 글자: str[0] 2. 나머지: str.slice(1) 3. 결합: 대문자 첫 글자 + 나머지 **"hello" 처리 과정** - str[0] → "h" - "h".toUpperCase() → "H" - str.slice(1) → "ello" - "H" + "ello" → "Hello" **빈 문자열 처리** 빈 문자열에서 str[0]은 undefined입니다. 이 경우 에러를 방지하기 위해 먼저 체크합니다: `if (!str) return str;` **toUpperCase()의 특성** 이미 대문자인 경우에도 에러 없이 그대로 반환합니다: "H".toUpperCase() → "H" **slice(1)의 특성** - 빈 문자열에서 slice(1)은 빈 문자열 반환 - 한 글자에서 slice(1)도 빈 문자열 반환 **대안: charAt(0)** `str[0]` 대신 `str.charAt(0)`도 사용할 수 있습니다. 빈 문자열에서 charAt(0)은 빈 문자열을 반환합니다.
Solution Code
function capitalize(str) {
if (!str) return str;
return str[0].toUpperCase() + str.slice(1);
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size