class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
class Solution {
public:
string toLowerCase(string s) {
for (char &c : s) {
if (c >= 'A' && c <= 'Z') {
c = c - 'A' + 'a';
}
}
return s;
}
};
class Solution {
public String toLowerCase(String s) {
return s.toLowerCase();
}
}
/**
* @param {string} s
* @return {string}
*/
var toLowerCase = function(s) {
return s.toLowerCase();
};
The "To Lower Case" problem asks you to convert all uppercase letters in a given string s
to their corresponding lowercase letters and return the resulting string. Non-alphabetic characters and lowercase letters should remain unchanged. You are guaranteed that the input will always be a valid string, and you should return a new string where all alphabetic characters are in lowercase.
s
At first glance, this problem seems simple: just change all the uppercase letters to lowercase. The most direct way is to use a built-in function, if available. However, if we were to do it manually, we would need to check each character, determine if it is uppercase, and convert it if necessary. This leads to thinking about how characters are represented (e.g., ASCII codes) and how to manipulate them efficiently.
A brute-force approach would involve iterating through each character and using conditional statements to check and convert as needed. But since this is a common operation, most languages provide optimized built-in methods. The challenge is to understand both approaches and why the built-in method is optimal.
s
.
Many programming languages provide a built-in function (like toLowerCase()
or lower()
) that performs these steps efficiently. Using the built-in method is preferred for clarity and performance, but knowing the manual approach helps understand what happens under the hood.
Design Justification: We use character iteration because strings are immutable in many languages, so creating a new string is necessary. Checking character ranges is efficient because it only involves integer comparisons.
Example Input: s = "Hello, WORLD!"
Final Output: "hello, world!"
toLowerCase()
or lower()
is also O(n) time and O(n) space, as the function must process each character and return a new string. The built-in method may be slightly faster due to internal optimizations.
The "To Lower Case" problem is a straightforward string manipulation task that leverages character-by-character processing. The optimal solution uses a built-in function for clarity and efficiency, but understanding the manual conversion helps build foundational programming skills. The approach is efficient, simple, and elegant, with both time and space complexities linear in the size of the input string.