题目:请实现一个函数,把字符串中的每个空格替换成"%20",例如输入"We are happy",输出"We%20are%20happy";
分析:首先计算出字符串中总共有多少空格,而后创建一个原先字符串长度加2倍空格的字符数组,通过从右向左的方式遍历原先字符串,遇到空格则替换成%20即可;
代码:
public class ReplaceSpace {
public String replaceSpace(StringBuffer str) {
if(str == null)
return null;
if(str.length() == 0)
return "";
//先找到有多少空格
int count = 0;
for(int i = 0;i < str.length();i++)
{
if(str.charAt(i) == ' ')
count++;
}
int len = str.length()+count*2;
char[] result = new char[len];
int index = len-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) {
ReplaceSpace demo = new ReplaceSpace();
System.out.println(demo.replaceSpace(new StringBuffer("We are Happy ")));
}
}
课后练习:
有两个排序的数组A和数组B,请实现一个函数,把B的所有数字插入到A中并且保证所有数字是有序的;
public class MergeArray {
public int[] mergeArray(int[] arrayA,int[] arrayB)
{
int[] result = new int[arrayA.length+arrayB.length];
if(arrayA == null && arrayB != null)
return arrayB;
else if(arrayA != null && arrayB == null)
return arrayA;
else if(arrayA == null && arrayB == null)
return null;
int indexA = 0;
int indexB = 0;
int index = 0;
while(indexA < arrayA.length && indexB < arrayB.length)
{
if(arrayA[indexA] <= arrayB[indexB])
{
result[index] = arrayA[indexA];
indexA++;
index++;
}else
{
result[index] = arrayB[indexB];
indexB++;
index++;
}
}
while(indexA < arrayA.length)
{
result[index] = arrayA[indexA];
indexA++;
index++;
}
while(indexB < arrayB.length)
{
result[index] = arrayB[indexB];
indexB++;
index++;
}
return result;
}
public static void main(String[] args) {
MergeArray demo = new MergeArray();
int[] arrayA = {1,3,5,7,9,10};
int[] arrayB = {2,4,6,8,10};
int[] result = demo.mergeArray(arrayA, arrayB);
for(int i = 0;i < result.length;i++)
System.out.print(result[i]+" ");
}
}