#3374
First Letter Capitalization II
HardDatabaseString ManipulationCharacter Processing
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach processes the string in a single pass, modifying characters directly. It efficiently handles hyphenated words and ensures minimal space usage.
⚙️
Algorithm
3 steps- 1Step 1: Traverse each character in the content_text.
- 2Step 2: Capitalize the first character of each word and handle hyphens appropriately.
- 3Step 3: Construct the modified string in a single pass.
solution.py13 lines
1def capitalize_words(content):
2 result = []
3 capitalize_next = True
4 for char in content:
5 if char == ' ':
6 result.append(char)
7 capitalize_next = True
8 elif capitalize_next:
9 result.append(char.upper())
10 capitalize_next = False
11 else:
12 result.append(char.lower())
13 return ''.join(result)ℹ
Complexity note: This approach is linear since it processes each character once, making it efficient.
- 1Handling special characters like hyphens is crucial.
- 2Maintaining original spacing is important.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.