一、利用StringBuffer或者StringBuilder
import java.util.*;
public class Solution {
public String replaceSpace (String s) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
sb.append("%20");
}else{
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}
二、采用数据结构
import java.util.*;
public class Solution {
public String replaceSpace (String s) {
if(s == null) {
return null;
}
StringBuffer sb = new StringBuffer(s);
int oldLength = sb.length();
int newLength = 0;
int spaceNum = 0;
for(int i = 0; i < oldLength; i++) {
if(sb.charAt(i) == ' ') {
spaceNum++;
}
}
int p1 = oldLength - 1;
int p2 = p1 + 2 * spaceNum;
sb.setLength(p2 + 1);
while(p2 >= 0 && spaceNum > 0) {
char c = sb.charAt(p1--);
if(c == ' ') {
sb.setCharAt(p2--, '0');
sb.setCharAt(p2--, '2');
sb.setCharAt(p2--, '%');
}else{
sb.setCharAt(p2--, c);
}
}
return sb.toString();
}
}