Post

Leetcode 0709. To Lower Case

Given a string `s`, return the string after replacing every uppercase letter with the same lowercase letter. Example 1:  Input: s = "Hello", Output: "hello"  Example 2:  Input: s = "here", Output: "here"  Example 3:  Input: s = "LOVELY", Output: "lovely" 

Description

Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    # Iteration
    # Time Complexity: BigO(N)
    # Space Complexity: BigO(1)
    def toLowerCase(self, s: str) -> str:
        res = ""
        for c in s:
            # ord(): find unicode of 'c' (inverse of ord(): chr())
            if ord('A') <= ord(c) <= ord('Z'):
                res += chr((ord(c) - ord('A')) + ord('a'))
            else:
                res += c
        return res
  • Can also use a String function: s.lower()
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Replace string
 * Time Complexity: BigO(N)
 * Space Complexity: BigO(1)
 */
function toLowerCase(s: string): string {
  const str = s.split("");
  for (let i = 0; i < str.length; i++) {
    if (str[i].charCodeAt(0) > 64 && str[i].charCodeAt(0) < 91)
      str[i] = String.fromCharCode(str[i].charCodeAt(0) + 32);
  }
  return str.join("");
}
  • Can also use a String function: s.toLowerCase()

Reference:

This post is licensed under CC BY 4.0 by the author.