一:题目
二:上码
class Solution {
public String replaceSpace(String s) {
if (s == null) return null;
StringBuilder str = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
str.append(" ");//增加两个空格
}
}
int oldl = s.length()-1;
s+=str;
int newl = s.length()-1;
char[] chars = s.toCharArray();//字符串转换成字符数组
for (int i = oldl,j = newl; i < j; i--,j--) {
if (chars[i] != ' ') {
chars[j] = chars[i];
} else {
chars[j] = '0';
chars[j-1] = '2';
chars[j-2] = '%';
j = j-2;
}
}
return new String(chars);
//错误用法
// for (int i = oldl,j = newl; i < j; i--,j--) {
// if (s.charAt(i) != ' ') {
// s.charAt(j) = s.charAt(i);
// } else {
// s.charAt(j) = '0';
// s.charAt(j-1) = '2';
// s.charAt(j-2) = '%';
// j = j-2;
// }
// }
// return s;
}
}