0709. 转换成小写字母【简单】
1. 📝 题目描述
给你一个字符串 s,将该字符串中的大写字母转换成相同的小写字母,返回新的字符串。
示例 1:
txt
输入:s = "Hello"
输出:"hello"1
2
2
示例 2:
txt
输入:s = "here"
输出:"here"1
2
2
示例 3:
txt
输入:s = "LOVELY"
输出:"lovely"1
2
2
提示:
1 <= s.length <= 100s由 ASCII 字符集中的可打印字符组成
2. 🎯 s.1 - 使用内置方法
js
/**
* @param {string} s
* @return {string}
*/
var toLowerCase = function (s) {
return s.toLowerCase()
}1
2
3
4
5
6
7
2
3
4
5
6
7
- 时间复杂度:
,其中 n 是字符串的长度 - 空间复杂度:
,需要创建新的字符串
3. 🎯 s.2 - ASCII 码转换
js
/**
* @param {string} s
* @return {string}
*/
var toLowerCase = function (s) {
let result = ''
for (let i = 0; i < s.length; i++) {
const char = s[i]
const code = char.charCodeAt(0)
// 判断是否为大写字母 (ASCII: 65-90)
if (code >= 65 && code <= 90) {
// 转换为小写字母 (ASCII: 97-122)
result += String.fromCharCode(code + 32)
} else {
result += char
}
}
return result
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
js
/**
* @param {string} s
* @return {string}
*/
var toLowerCase = function (s) {
const chars = s.split('')
for (let i = 0; i < chars.length; i++) {
const code = chars[i].charCodeAt(0)
// 判断是否为大写字母
if (code >= 65 && code <= 90) {
chars[i] = String.fromCharCode(code + 32)
}
}
return chars.join('')
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 时间复杂度:
,其中 n 是字符串的长度,需要遍历每个字符 - 空间复杂度:
,需要创建新的字符串存储结果