剑指 Offer 05. 替换空格

请实现一个函数,把字符串 s 中的每个空格替换成”%20”。

示例 1:

1
2
输入:s = "We are happy."
输出:"We%20are%20happy."

限制:

1
0 <= s 的长度 <= 10000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:sarizzm time:2021/1/6 0006


# 暴力求解

class Solution:
def replaceSpace(self, s):
if s is None:
return s

st = str()
for i in s:
if i ==' ':
st += '%20'
else:
st += i
return st



print(Solution().replaceSpace('We are happy.'))


执行用时:40 ms, 在所有 Python3 提交中击败了51.35%的用户

内存消耗:14.8 MB, 在所有 Python3 提交中击败了10.11%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public String replaceSpace(String s) {
int length = s.length();
char[] array = new char[length * 3];
int size = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == ' ') {
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
} else {
array[size++] = c;
}
}
String newStr = new String(array, 0, size); // 数组技巧的操作
return newStr;
}
}


//作者:LeetCode-Solution
//链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-by-leetcode-solutio/