题目:用‘%20’替换空格
解法1 :重新申请一个数组存放插入后的数据
解法分析:增加了一个数组,空间复杂度O(n),遍历一遍数组,时间复杂度O(n)。
package demo.test;
public class Test {
public static String replace(StringBuilder sb) {
String str = sb.toString();
char[] charBefore = str.toCharArray();
int count = 0;
for (char ch : charBefore) {
if(ch == ' ')
count++;
}
int length = charBefore.length + 2*count;
char[] charAfter = new char[length];
int j = length-1;
for(int i = charBefore.length-1 ; i>=0; i--) {
if(charBefore[i]!=' ') {
charAfter[j] = charBefore[i];
j--;
}
else {
charAfter[j] = '0';
j--;
charAfter[j] = '2';
j--;
charAfter[j] = '%';
j--;
}
}
if(j==-1 ) {
return String.valueOf(charAfter);
}
return "error";
}
public static void main(String[] args) {
String str = "we are happy";
StringBuilder sb = new StringBuilder(str);
String rep = replace(sb);
System.out.println(rep);
}
}
解法2:只在原数组上扩展为新的数组,从后往前扩展。
解法分析:空间复杂度没有增加,遍历一遍数组,时间复杂度为O(n)。
package demo.test;
public class Test {
public static String replace(StringBuilder str) {
if(str == null)
return null;
int count = 0;
for(int i =0;i<str.length();i++){
if(str.charAt(i) == ' ')
count++;
}
int lengthOld = str.length();
int lengthNew = str.length()+2*count;
int i = lengthOld-1;
int j = lengthNew-1;
str.setLength(lengthNew);
for( ;i>=0;i--){
if(str.charAt(i)!=' '){
str.setCharAt(j--,str.charAt(i));
}
else {
count--;
str.setCharAt(j--,'0');
str.setCharAt(j--,'2');
str.setCharAt(j--,'%');
}
if(count == 0)
break;
}
return str.toString();
}
public static void main(String[] args) {
String str = "we are happy";
StringBuilder sb = new StringBuilder(str);
String rep = replace(sb);
System.out.println(rep);
}
}
————————分割线—————————————————————————-
扩展题:
题目:将两个有序的数组合并成一个有序的数组。
解法分析:沿用上面解法2,从后向前比较两个数组中的元素,然后插入元素。
package demo.test;
import java.util.ArrayList;
public class Test {
public static String replace(ArrayList<Integer> array1,ArrayList<Integer> array2) {
if(array1 == null || array2 == null)
return null;
int lengthNew = array1.size() + array2.size();
int k = lengthNew -1;
int i = array1.size()-1;
int j = array2.size()-1;
array1.addAll(array2);//扩展原数组
while(i>=0 && j>=0) {
if(array1.get(i)>array2.get(j)) {
array1.set(k, array1.get(i));
k--;
i--;
}
else {
array1.set(k, array2.get(j));
k--;
j--;
}
}
while(i>=0) {
array1.set(k, array1.get(i));
i--;
}
while(j>=0) {
array1.set(k, array2.get(j));
j--;
}
return array1.toString();
}
public static void main(String[] args) {
ArrayList<Integer> array1 = new ArrayList<Integer>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
array1.add(1);
array1.add(3);
array1.add(6);
array2.add(2);
array2.add(4);
array2.add(5);
array2.add(7);
System.out.println(replace(array1,array2));
}
}