剑指 Offer 05. 替换空格

题目

剑指 Offer 05. 替换空格

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

示例 1:

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

题解

python解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def replaceSpace(self, s):
L = []
last = 0
for i in range(len(s)):
if s[i] == " ":
L.append(s[last:i]+"%20")
last = i+1
if last < len(s):
L.append(s[last:len(s)])
return "".join(L)

if __name__ == '__main__':
a = Solution()
print(a.replaceSpace("I am the Only King!"))
print(a.replaceSpace(" "))

java解法

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
26
package Slash_offer.easy;

public class Slash_offer_05 {

public static void main(String[] args) {
Slash_offer_05 slash_offer_05 = new Slash_offer_05();
System.out.println(slash_offer_05.replaceSpace("I am the king"));
System.out.println(slash_offer_05.replaceSpace(" "));

}
public String replaceSpace(String s) {
int length = s.length();
char [] res = new char[3 * length];
int j = 0 ;
for (int i = 0; i < length; i++) {
if (' '==(s.charAt(i))){
res[j++] = '%';
res[j++] = '2';
res[j++] = '0';
}else{
res[j++] = s.charAt(i);
}
}
return new String(res,0,j);
}
}