题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路
如果直接开始遍历进行替换,每次替换一个空格都需要将字符串空格后面部分整体进行后移,因而效率比较低。
正确解题方法,先遍历字符串得到一共有多少个空格,假设有x个,那么新串的长度应该为 原字符串长度+x*2。
知道新串长度之后,从后向前遍历原串对新串进行填充就可以了,遇到空格则填充%20。
public class tihuankongge {
public String replaceSpace(StringBuffer str) {
if (str == null)
return null;
int spaceCount = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spaceCount++;
}
}
char[] result = new char[str.length() + spaceCount*2];
int index = result.length - 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) != ' ') {
result[index--] = str.charAt(i);
} else {
result[index--] = '0';
result[index--] = '2';
result[index--] = '%';
}
}
return new String(result);
}
public static void main(String[] args) {
System.out.println(new tihuankongge().replaceSpace(new StringBuffer("hello word")));
}
}