709. To Lower Case
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.
💡 Hint 1:
Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily.
💡 Hint 2:
Think ASCII!
💡 Hint 3:
Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use?
Submitted Code
class Solution(object):
def toLowerCase(self, s):
"""
:type s: str
:rtype: str
"""
ascii_A = 65
ascii_a = 97
diff = ascii_a - ascii_A # 32
result = []
for ch in s:
ascii_num = ord(ch) # 문자 → 아스키코드
if ascii_A <= ascii_num <= (ascii_A + 25):
result.append(chr(ascii_num + diff)) # 아스키코드 → 문자
else:
result.append(ch)
return "".join(result)
Runtime: 0 ms | Beats 100.00%
Memory: 12.50 MB | Beats 51.83%
Z
이후 특수기호들이 몇 개 존재하기 때문에 A
와 a
의 아스키코드 값 차이는 32가 된다.
Other Solutions
1st
class Solution(object):
def toLowerCase(self, s, method="builtin"):
result = ""
for c in s:
if 'A' <= c <= 'Z':
result += chr(ord(c) + 32)
else:
result += c
return result
time complexity: 𝑂(𝑛)
space complexity: 𝑂(𝑛)
문자(char)형은 아스키코드 또는 유니코드 값을 갖고 있기 때문에 'A' <= c <= 'Z'
으로 간단하게 비교할 수 있다.