709. To Lower Case
Description
Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.
Example 1:
Input: s = "Hello" Output: "hello"
Example 2:
Input: s = "here" Output: "here"
Example 3:
Input: s = "LOVELY" Output: "lovely"
Constraints:
1 <= s.length <= 100sconsists of printable ASCII characters.
Solutions
Solution 1
Thinking
Convert uppercase letters to lowercase; \(n \le 100\). A library call works, and so does an ASCII walk.
Each uppercase letter is \(32\) below its lowercase counterpart, i.e. bit \(5\) of the code point. Bitwise-or with \(32\) lowercases it; other characters stay unchanged.
Map every character: if it is uppercase, emit \(\operatorname{ord}(c)\,|\,32\). Time \(O(n)\).
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 | |
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 9 | |
Solution 2
Thinking
Solution 1 branches on isupper. Lowercase ASCII already has bit \(5\) set, so or-ing \(32\) is a no-op there and we can apply it uniformly.
The TypeScript tab ors every character; the Rust tab still guards \(A\)–\(Z\) so non-letters are untouched. Neither version calls a locale-aware lowercasing API.
1 2 3 | |
1 2 3 4 5 6 7 8 | |