题目及测试
package sword004;
/*
* 题目描述: 请实现一个函数,将字符串的每个空格替换为"%20"。
* 例如输入"We are happy",则输出"We%20are%20happy."。
*/
public class main {
public static void main(String[] args) {
String [] testTable = {"hello","A man, a plan, a canal: Panama","av12,./34\\45"};
for (String ito : testTable) {
test(ito);
}
}
private static void test(String ito) {
Solution solution = new Solution();
String rtn;
long begin = System.currentTimeMillis();
System.out.print(ito);
System.out.println();
//开始时打印数组
rtn= solution.replace(ito);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn=" );
System.out.print(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功)
先计算input中空格的数目count,然后建立大小为length+2*count的新char数组,然后双指针遍历新旧数组,给新数组赋值,遇到旧数组的空格,就新数组设置3个值。
package sword004;
import java.util.Arrays;
public class Solution {
public String replace(String input) {
if(input == null) {
return input;
}
int length = input.length();
if(length ==0) {
return input;
}
int count =0;
for(int i=0;i<length;i++) {
if(input.charAt(i) == ' ') {
count++;
}
}
if(count == 0) {
return input;
}
int totalLength = length +2 * count;
char[] array = new char[totalLength];
int j = 0;
for(int i=0;i<length;i++) {
if(input.charAt(i) == ' ') {
array[j++] = '%';
array[j++] = '2';
array[j++] = '0';
}else {
array[j++] = input.charAt(i);
}
}
return new String(array);
}
}