This content originally appeared on DEV Community and was authored by seanpgallivan
This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode's forums.
Leetcode Problem #709 (Easy): To Lower Case
Description:
(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)
Given a string
s
, return the string after replacing every uppercase letter with the same lowercase letter.
Examples:
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 <= 100
s
consists of printable ASCII characters.
Idea:
(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)
The uppercase letters from 'A' to 'Z' have ASCCII codes between 65 and 90. We can iterate through our input string (s) and as we build up our answer string (ans), if the value (n) of any character lies in that range, we can replace it with the character of value n + 32, which corresponds to the lowercase version of the uppercase letter.
- Time Complexity: O(N) where N is the length of s
- Space Complexity: O(1) excluding the space of the output
Javascript Code:
(Jump to: Problem Description || Solution Idea)
var toLowerCase = function(s) {
let ans = ""
for (let c of s) {
let n = c.charCodeAt()
ans += n > 64 && n < 91 ? String.fromCharCode(n + 32) : c
}
return ans
};
Python Code:
(Jump to: Problem Description || Solution Idea)
class Solution:
def toLowerCase(self, s: str) -> str:
ans = ""
for c in s:
n = ord(c)
ans += chr(n+32) if n > 64 and n < 91 else c
return ans
Java Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
public String toLowerCase(String s) {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
ans.append(c > 64 && c < 91 ? (char)(c + 32) : c);
}
return new String(ans);
}
}
C++ Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
public:
string toLowerCase(string s) {
string ans = "";
for (auto& c : s)
ans += c > 64 && c < 91 ? c + 32 : c;
return ans;
}
};
This content originally appeared on DEV Community and was authored by seanpgallivan
seanpgallivan | Sciencx (2021-05-24T08:08:41+00:00) Solution: To Lower Case. Retrieved from https://www.scien.cx/2021/05/24/solution-to-lower-case/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.