-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.java
More file actions
29 lines (29 loc) · 850 Bytes
/
2.java
File metadata and controls
29 lines (29 loc) · 850 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
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str==null || str.length()==0) return str.toString();
//从前向后统计空格的数量
int count=0;
int old_length=str.length();
for(int i=0;i<old_length;i++)
{
if(str.charAt(i)==' ') count++;
}
str.setLength(str.length()+2*count);
//从后向前替换空格
for(int i=old_length-1;i>=0;i--)
{
if(str.charAt(i)!=' ')
{
str.setCharAt(i+2*count,str.charAt(i));
}
else
{
count--;
str.setCharAt(i+2*count,'%');
str.setCharAt(i+2*count+1,'2');
str.setCharAt(i+2*count+2,'0');
}
}
return str.toString();
}
}