Leetcode 709 - To Lower Case

Problem Statement

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example 1:

Input: “Hello”
Output: “hello”

Example 2:

Input: “here”
Output: “here”

Example 3:

Input: “LOVELY”
Output: “lovely”

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def toLowerCase(self, str):
l = ""
for c in str:
ascii = ord(c)
if ascii >= 65 and ascii <= 90:
ascii += 32
l += chr(ascii)
return l

Time: O(str.Length)

Space: O(str.Length)

Explanation:

Lower case ascii values are between 97 (‘a’) and 122 (‘z’) and upper case values are between 65 (‘A’) and 90 (‘Z). The difference between the two ranges is 32 so simply getting the current character’s ascii value and adding 32 if it is between 65 and 90 will convert the character to its lower case value, otherwise it will remain the same kind of character.