您的位置:首页 > Web前端

替换字符--《剑指offer》

2017-01-14 20:27 169 查看
题目描述:给定一个字符数组,将其中的某一字符替换为其他几个字符;如we are tf将空格替换为%20,结果为we%20are%20tf(字符数组后有足够位置)

分析:如果从前往后替换则一些字符会多次移动浪费时间,如果能一次将其放入位置一定会减少资源利用的

思路:遍历一遍算出每个字符要移动到的位置,以便一次移动到目标位置

实现:

public static void replaceBlack(char s[]){
int i=0,length=0,count=0;
while(s[i]!='\0'){
if(s[i]==' '){
count++;
}
length++;
i++;

}
if(s==null||length==0)
return;
int last=count*2+length-1,pre=length-1;
while(pre!=last){
if(s[pre]!=' '){
s[last]=s[pre];
last--;
pre--;
}
else{
s[last--]='0';
s[last--]='2';
s[last--]='%';
pre--;
}
}
}

主调函数:

public static void main(String[] args) {
// TODO Auto-generated method stub
char[] s=new char[100];
s[0]='w';
s[1]='e';
s[2]=' ';
s[3]='a';
s[4]='r';
s[5]='e';
s[6]=' ';
s[7]='w';
s[8]='t';
s[9]='\0';
replaceBlack(s);
System.out.println(s);

}

结果:we%20are%20wt

相似案例:合并有序数组AB,结果放在A后面

实现:

public static void merge(int a[],int b[]){
int al=0,bl=0;
int i=0,last,prea,preb;
if(a==null||b==null)
return;
while(a[i]!='\0'){
al++;
i++;
}
i=0;
while(b[i]!='\0'){
bl++;
i++;
}
last=al+bl-1;
prea=al-1;
preb=bl-1;
if(prea==0||preb==0)
return;
while(prea>=0&&preb>=0){
if(a[prea]>b[preb]){
a[last]=a[prea];
last--;
prea--;
}
else{
a[last]=b[preb];
last--;
preb--;
}
}
while(preb>=0){
a[last]=b[preb];
preb--;
}
}


主调函数:

public static void main(String[] args) {
// TODO Auto-generated method stub
int [] a=new int[100];
int [] b=new int[100];
a[0]=1;
a[1]=3;
a[2]=5;
a[3]='\0';
b[0]=2;
b[1]=4;
b[2]=4;
b[3]=9;
b[4]='\0';
merge(a, b);
for(int k=0;k<10;k++){
System.out.print(a[k]);
}
}


结果:1234459000

总结:遇到案例后如果有多次执行一个操作后到目标状态,应该想想是否可以一次可以到达目标状态。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法