709. 转换成小写字母
LeetCode: 709. 转换成小写字母
简 单 \color{#00AF9B}{简单} 简单
给你一个字符串
s
,将该字符串中的大写字母转换成相同的小写字母,返回新的字符串。
示例 1:
输入:s = "Hello"
输出:"hello"
示例 2:
输入:s = "here"
输出:"here"
示例 3:
输入:s = "LOVELY"
输出:"lovely"
提示:
1 <= s.length <= 100
s
由 ASCII 字符集中的可打印字符组成
方法1:使用编程语言内置的API
每个编程语言大都有内置API可以实现大写与小写字母的转换,C++中即为 tolower
函数。
#include <string>
using namespace std;
class Solution
{
public:
string toLowerCase(string s)
{
for (char &c : s)
{
c = tolower(c);
}
return s;
}
};
复杂度分析
-
时间复杂度: O ( n ) O(n) O(n)
-
空间复杂度: O ( 1 ) O(1) O(1)。我们只需要常量空间来存储若干变量。
参考结果
Accepted
114/114 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 9.99 % of cpp submissions (6.1 MB)
方法2:加减法
#include <string>
using namespace std;
class Solution
{
public:
string toLowerCase(string s)
{
for (char &c : s)
{
if ('A' <= c && c <= 'Z')
c = c - 'A' + 'a';
}
return s;
}
};
复杂度分析
-
时间复杂度: O ( n ) O(n) O(n)
-
空间复杂度: O ( 1 ) O(1) O(1)。我们只需要常量空间来存储若干变量。
参考结果
Accepted
114/114 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 18.46 % of cpp submissions (6.1 MB)
方法3:位运算
其实ASCII码表对于大小写之间的关系制定是有说法的。
- 大写字母 A - Z 的 ASCII 码范围为 [65, 90]:
- 小写字母 a - z 的 ASCII 码范围为 [97, 122]。
可以发现每个小写字母和其对应的大写字母间差值为 32
:'a'-'A'=32
。这是一个很特殊的数字,因为32是2的次幂。
- 32所对应的二进制为 ( 100000 ) (100000) (100000)
- [65,90]所对应的二进制为 [ ( 01000001 ) 2 , ( 01011010 ) 2 ] [(01000001)_2 ,(01011010)_2 ] [(01000001)2,(01011010)2]
- [97, 122]所对应的二进制为 [ ( 01100001 ) 2 , ( 01111010 ) 2 ] [(01100001)_2 ,(01111010)_2 ] [(01100001)2,(01111010)2]
可以发现,将大写字母的二进制的第 5
位(从0计数)改成 1
即可得到其对应的小写字母。从这里是能看出ASCII码表对大小写字母的排列不是随便排的,大小写的转换只要在二进制的第 5
位上动手脚即可。
#include <string>
using namespace std;
class Solution
{
public:
string toLowerCase(string s)
{
for (char &c : s)
{
if (c >= 65 && c <= 90)
c |= 32;
}
return s;
}
};
复杂度分析
-
时间复杂度: O ( n ) O(n) O(n)
-
空间复杂度: O ( 1 ) O(1) O(1)。我们只需要常量空间来存储若干变量。
参考结果
Accepted
114/114 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 71.81 % of cpp submissions (6 MB)