题目:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy,则经过替换之后的字符串为We%20Are%20Happy。
public class TestMethod5_1 {
public static void main(String[] args) {
String str = "We Are Happy.";
System.out.println(method(new StringBuilder(str)));
}
public static String method(StringBuilder str) {
if (str == null || str.length() == 0) return null;
int spaceNumber = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') spaceNumber++;
}
int oldIndex = str.length() - 1;
int newLength = str.length() + spaceNumber * 2;
int newIndex = newLength - 1;
str.setLength(newLength);
while (oldIndex >= 0 && newIndex > oldIndex) {
if (str.charAt(oldIndex) == ' ') {
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
} else {
str.setCharAt(newIndex--, str.charAt(oldIndex));
}
oldIndex--;
}
return str.toString();
}
}
解题思路
复杂度分析
题目:有两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中所有数字插入A1中,并且所有的数字都是排序的。例如:输入A1=>{1, 2, 3, 4},A2=>{2, 4, 6},输出A1=>{1, 2, 2, 3, 4, 4, 6}。
public class TestMethod5_2 {
public static void main(String[] args) {
int[] A1 = new int[7];
A1[0] = 1;
A1[1] = 2;
A1[2] = 3;
A1[3] = 4;
int[] A2 = {2, 4, 6};
method(A1, 4, A2);
}
public static int[] method(int[] A1, int length, int[] A2) {
if (A1 == null || A1.length <= 0) return null;
if (A2 == null || A2.length <= 0) return null;
if (A1.length < (length + A2.length)) return null;
int a = length - 1;
int b = A2.length - 1;
int len = a + b + 1;
while (a >= 0 && b >= 0) {
A1[len--] = A1[a] > A2[b] ? A1[a--] : A2[b--];
}
return A1;
}
}
解题思路
复杂度分析