时间复杂度O(n) 空间复杂度O(1)
package com.basic;
public class ReplaceBlank {
public static void main(String[] args) {
char[] s=new char[50];
String str="we are happy";
int i = 0;
for (; i < str.length(); i++) {
s[i] = str.charAt(i);
}
s[i]='\0';
for(int j=0;s[j]!='\0';j++){
System.out.print(s[j]+" ");
}
System.out.println();
replace(s,50);
System.out.println("------------------换行-----------------------");
for(int j=0;s[j]!='\0';j++){
System.out.print(s[j]+" ");
}
}
public static void replace(char [] string,int length){
if(string==null||length<=0){
throw new IllegalArgumentException("参数不正确");
}
int originalLength=0;
int numberofBlank=0;
int i=0;
while(string[i]!='\0'){
originalLength++;
if(string[i]==' '){
numberofBlank++;
}
i++;
}
int newLength=originalLength+numberofBlank*2;
if(newLength>length){
throw new RuntimeException("数组长度不够");
}
int p1=originalLength;
int p2=newLength;
while(p1>=0 && p2>p1){
if(string[p1]==' '){
string[p2--]='0';
string[p2--]='2';
string[p2--]='%';
}else{
string[p2--]=string[p1];
}
--p1;
}
}
}
此代码思路来自剑指offer面试题
|