Welcome to Subscribe On Youtube
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: Direct Implementation
We can loop through the string and for each uppercase letter, convert it to lowercase. Finally, the converted string is returned.
Time complexity $O(n)$, where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$.
Solution 2
This implementation follows the required operations directly. A keyed container records values that must be found or updated efficiently. After all required states have been considered, the maintained result is returned.
-
class Solution { public String toLowerCase(String s) { char[] cs = s.toCharArray(); for (int i = 0; i < cs.length; ++i) { if (cs[i] >= 'A' && cs[i] <= 'Z') { cs[i] |= 32; } } return String.valueOf(cs); } } -
class Solution { public: string toLowerCase(string s) { for (char& c : s) { if (c >= 'A' && c <= 'Z') { c |= 32; } } return s; } }; -
class Solution: def toLowerCase(self, s: str) -> str: return "".join([chr(ord(c) | 32) if c.isupper() else c for c in s]) -
func toLowerCase(s string) string { cs := []byte(s) for i, c := range cs { if c >= 'A' && c <= 'Z' { cs[i] |= 32 } } return string(cs) } -
function toLowerCase(s: string): string { return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); } // Solution 2 function toLowerCase(s: string): string { return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); } -
impl Solution { pub fn to_lower_case(s: String) -> String { s.as_bytes() .iter() .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) .collect() } } // Solution 2 impl Solution { pub fn to_lower_case(s: String) -> String { s.as_bytes() .iter() .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) .collect() } } -
char* toLowerCase(char* s) { int n = strlen(s); for (int i = 0; i < n; i++) { if (s[i] >= 'A' && s[i] <= 'Z') { s[i] |= 32; } } return s; }