LeetCode-面试题05-替换空格
# LeetCode-面试题05-替换空格
请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例:
输入:s = "We are happy."
输出:"We%20are%20happy."
1
2
2
1
2
2
# 解题思路
方法1、遍历的时候直接用StringBuilder添加字符,遍历到空格的时候就添加%20,最后把char转化为String类型就可以了
方法2、利用python特点,一行解决= =
# Java代码
class Solution {
public String replaceSpace(String s) {
StringBuilder result = new StringBuilder();
for (char i : s.toCharArray()) {
if (i == ' ') {
result.append("%20");
} else
result.append(i);
}
return result.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# Python代码
class Solution(object):
def replaceSpace(self, s):
"""
:type s: str
:rtype: str
"""
return ''.join(('%20' if c == ' ' else c for c in s))
1
2
3
4
5
6
7
2
3
4
5
6
7
1
2
3
4
5
6
7
2
3
4
5
6
7
编辑 (opens new window)
上次更新: 2022/11/18, 11:15:10
- 01
- SpringCache基本配置类05-16
- 03
- Rpamis-security-原理解析12-13