-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution005.java
More file actions
41 lines (32 loc) · 951 Bytes
/
Solution005.java
File metadata and controls
41 lines (32 loc) · 951 Bytes
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.portgas;
public class Solution005 {
/**
* 将一个字符串中的空格替换成 "%20"。
**/
public String replaceSpace(StringBuffer str) {
int before = str.length();
for (int i = 0; i < before; i++) {
if (str.charAt(i) == ' ') {
str.append("12");
}
}
int after = str.length();
int p1 = before - 1;
int p2 = after - 1;
while (p1 >= 0) {
char c = str.charAt(p1--);
if (c == ' ') {
str.setCharAt(p2--, '0');
str.setCharAt(p2--, '2');
str.setCharAt(p2--, '%');
} else {
str.setCharAt(p2--, c);
}
}
return str.toString();
}
// 耗时比上面的方法高,参考test
public String replaceSpace2(StringBuffer str) {
return str.toString().replaceAll(" ", "%20");
}
}