title | description | keywords | ||||||
---|---|---|---|---|---|---|---|---|
709. 转换成小写字母 |
LeetCode 709. 转换成小写字母题解,To Lower Case,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。 |
|
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.
给你一个字符串 s
,将该字符串中的大写字母转换成相同的小写字母,返回新的字符串。
示例 1:
输入: s = "Hello"
输出: "hello"
示例 2:
输入: s = "here"
输出: "here"
示例 3:
输入: s = "LOVELY"
输出: "lovely"
提示:
1 <= s.length <= 100
s
由 ASCII 字符集中的可打印字符组成
-
内置方法:
- 可以直接使用 JavaScript 的
String.prototype.toLowerCase()
方法,快速实现字符串的小写转换。 toLowerCase()
会将字符串中所有大写字母转为小写,非字母字符保持不变。
- 可以直接使用 JavaScript 的
-
手动实现:
- 如果不使用内置方法,则需要遍历字符串,手动将大写字母转为小写字母。
- 可以利用 ASCII 码:
- 大写字母的 ASCII 范围为
65
(A
) 到90
(Z
)。 - 小写字母的 ASCII 范围为
97
(a
) 到122
(z
)。 - 小写和大写字母的差值为
32
,因此可以通过charCodeAt()
和String.fromCharCode()
转换字符。
- 大写字母的 ASCII 范围为
- 时间复杂度:
O(n)
,其中n
是字符串的长度。 - 空间复杂度:
O(n)
,用于存储转换后的字符串。
::: code-tabs @tab 使用内置方法
/**
* @param {string} s
* @return {string}
*/
var toLowerCase = function (s) {
return s.toLowerCase();
};
@tab 手动实现
/**
* @param {string} s
* @return {string}
*/
var toLowerCase = function (s) {
let result = '';
for (let char of s) {
let code = char.charCodeAt(0);
// 如果是大写字母,则转换为小写
if (code >= 65 && code <= 90) {
result += String.fromCharCode(code + 32);
} else {
result += char;
}
}
return result;
};
:::
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
2129 | 将标题首字母大写 | [✓] | 字符串 |
🟢 | 🀄️ 🔗 |