题目给你一串字符串如“”a b n n b “”将其中的空格替换成@?%
通常我们做的算法为将数组遍历 然后把空格替换 并将后面字符后移 此时时间复杂度为O(n2) 这往往达不到效率 那么怎么让时间复杂度为O(n)呢
给点提示 开辟一个新的空间。。。。。。。。。。。。
大家可能会恍然大悟 眼来这样 那么直接贴代码
public static void Replace(char[] str){
int oldlength=str.length;
int number=0;
for(int i=0;i<oldlength;i++){
if(str[i]==' '){
++number;
}
}
int newLength=number*2+oldlength;
// System.out.println("长度为"+newLength);
char[] temp=new char[newLength];
int a=5;
int b=9;
while(a>=0&&b>=a){
if(str[a]==' '){
temp[b--]='%';
temp[b--]='@';
temp[b--]='^';
}else{
System.out.println(str[a]);
temp[b--]=str[a];
}
--a;
}
}
现在是不是减少了时间的浪费了