题目
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
解答
public static String replaceSpace(String s) {
char[] ss = s.toCharArray();
int m = ss.length, count = 0;
// 统计字符串的空格数
for (int i = 0; i < m; i++) {
if(ss[i] == ' ')
count++;
}
int n = m + 2 * count;
char[] sss = new char[n];
int i = m - 1, j = n - 1;
while(i >= 0){
if(ss[i] != ' '){
sss[j] = ss[i];
i--;
j--;
}else{
sss[j] = '0';
sss[j-1] = '2';
sss[j-2] = '%';
i--;
j -= 3;
}
}
return String.valueOf(sss);
}