题目描述:
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
思路分析:1)直接使用JDK自带的replace()方法;2)从后往前逐个替换:首先遍历字符串,统计空格数量;建立字符数组,新数组的长度应该为原数组长度+2*空格数量,因为1个空格变为%20长度加2;
代码:
1)使用JDK自带方法
class Solution {
public String replaceSpace(String s) {
String temp = s.replace(" ","%20");
return temp;
}
}
2)逐个替换
class Solution {
public String replaceSpace(String s) {
int count = 0;
for(int i = 0 ; i < s.length() ; i++ ){
if(s.charAt(i)==' ')
count ++;
}
int newlength = 2*count + s.length();
char[] temp = new char[newlength];
for(int i = s.length() -1 ; i >= 0 ; i-- ){
if(s.charAt(i) != ' '){
temp[i + 2*count] = s.charAt(i);
} else {
count--;
temp[i + 2*count + 2] = '0';
temp[i + 2*count + 1] = '2';
temp[i + 2*count] = '%';
}
}
String str = new String(temp);
return str;
}
}