To Lower Case (Leetcode 709)

Difficulty: Easy Link: Day 24: May Leetcode Challenge

Problem Description

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

Examples

Input: s = "Hello"
Output: "hello"
Input: s = "here"
Output: "here"
Input: s = "LOVELY"
Output: "lovely"

Constraints

  • 1 <= s.length <= 100
  • s consists of printable ASCII characters.

Solution

The solution is quite straight forward and you might be tempted to use the built-in functions to convert the string directly to lowercase using lowercased(). However, the interviewer might be interested in how you implement it so you should try to solve with your own implementation.

We can easily implement our lowercase function using the fact the ASCII values of lowercase and uppercase alphabets differ by 32 ( ‘A’ = 65, ‘B’ = 66 … ‘a’ = 98, ‘b’ = 99.. so on ).

Swift

class Solution {
func toLowerCase(_ s: String) -> String {
var result = ""
for c in s {
var letter = c
if c >= "A", c <= "Z" {
letter = toLower(c)
}
result += "\(letter)"
}
return result
}
func toLower(_ character:Character) -> Character {
let asciiValue:UInt8 = character.asciiValue! + 32
return Character(UnicodeScalar(asciiValue))
}
}
view raw to_lower_case.swift hosted with ❤ by GitHub

Python

class Solution:
def toLowerCase(self, str: str) -> str:
is_upper = lambda x : 'A' <= x <= 'Z'
to_lower = lambda x : chr(ord(x) | 32)
return ''.join([to_lower(x) if is_upper(x) else x for x in str])
view raw to_lower_case.py hosted with ❤ by GitHub

Java

class Solution {
public boolean isUpper(char x) {
return 'A' <= x && x <= 'Z';
}
public char toLower(char x) {
return (char) ((int)x | 32);
}
public String toLowerCase(String str) {
StringBuilder sb = new StringBuilder();
for (char x : str.toCharArray()) {
sb.append(isUpper(x) ? toLower(x) : x);
}
return sb.toString();
}
}
view raw to_lower_case.java hosted with ❤ by GitHub

Complexity Analysis

  • Time complexity: O(N) to parse the input string.
  • Space complexity: O(N) to keep the output.

Leave a Reply

Your email address will not be published. Required fields are marked *