超琐碎 ≈ 完整记录 + 深入探究 + 任性吐槽
问题地址,难度:Easy,标签:String
若有错误之处请予以指正:)
问题描述
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"
题意分析
在Python里这个需求完全就是调一个内置函数的事,然而如果自己要实现呢?
我的实现及调优过程
方法1:32 ms
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
时间复杂度:N/A
空间复杂度:N/A
方法2:40 ms
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
sub = ord('a') - ord('A') # 32
return ''.join([char if ord(char) not in range(65, 91)
else chr(ord(char)+sub) for char in str])
自己实现需要知道Ascii码的一些基本知识(大小写字符间的差值为32),以及Python中字符与ASCII码之间的转换函数ord()和chr()
时间复杂度:O(n)
空间复杂度:O(n)