[
string
]
Leetcode 0709. To Lower Case
Problem statement
https://leetcode.com/problems/to-lower-case/
Solution
I assume here, that we can not use lower()
function, because in the opposite case we can just return s.lower()
. If we are not allowed to do it on real interview: we need to traverse our string and look at symbols. What we need to do is to make each capital letter small letter, that is A -> a, B -> b, ... Z -> z
. Codes of all small letters are adjacent and codes of all capital letters are adjacent too, so to make capital letter small, we can use chr(ord(i) + 32)
, where 32 = ord("a") - ord("A")
. Then we just combine our string back.
Complexity
Time and space complexity is O(n)
, where n
is the length of s
.
Code
class Solution:
def toLowerCase(self, s):
return "".join(chr(ord(i) + 32) if "A" <= i <= "Z" else i for i in s)