Leetcode 709. To Lower Case
Problem Statement
Given a string s
, convert it to lowercase. The function should return a new string that contains the same characters as s
, but all converted to lowercase.
Example:
- Input: “Hello”
-
Output: “hello”
- Input: “here”
-
Output: “here”
- Input: “LOVELY”
- Output: “lovely”
You need to implement a function with the following signature:
string toLowerCase(string s);
Clarifying Questions
- Q: Can the input string include numbers or special characters?
- A: Yes, the input string can include any ASCII characters.
- Q: Should the function handle empty strings?
- A: Yes, the function should return an empty string if the input is empty.
- Q: Is there a limit to the length of the input string?
- A: There is no explicit limit mentioned, but it can be assumed it fits within standard constraints (e.g., typical constraints might be up to 10^4 characters).
Strategy
- Traversal and Conversion:
- Traverse each character of the string.
- For each character, check if it is an uppercase letter (between ‘A’ and ‘Z’).
- If it is uppercase, convert it to its corresponding lowercase character by adding the difference between ‘a’ and ‘A’ to it.
- Append the resulting character to a new string.
- ASCII Value Utilization:
- The conversion from uppercase to lowercase can be done using ASCII values:
- For any uppercase letter
ch
, its lowercase can be calculated using ch + ('a' - 'A')
.
- Edge Cases:
- An empty string should be handled by simply returning an empty string.
- If the string contains non-alphabetic characters (numbers or special characters), they should remain unchanged.
Code
#include <string>
using namespace std;
string toLowerCase(string s) {
string result;
for (char ch : s) {
if (ch >= 'A' && ch <= 'Z') {
result += ch + ('a' - 'A');
} else {
result += ch;
}
}
return result;
}
Time Complexity
- Time Complexity: O(n), where n is the length of the input string
s
. Each character is processed exactly once.
- Space Complexity: O(n), where n is the length of the input string
s
. This is due to the storage required for the resultant string.
This approach ensures that the function efficiently handles the conversion with a straightforward traversal and ASCII value manipulation.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?