题目示例:把字符串中的每个空格替换成“%20”。例如输入“who are you",则输出”who%20are%20you"
/**
* @author Administrator* 首先,我们明确需要得到一个时间复杂度在o(n)的算法。
* 添加后的字符串的长度为为原长度+空格的个数*2
* 思路,我们定义两个尾指针,指向老字符串和新字符串的末尾。
*
*/
public class space_replace {
public static void main(String args[]){
char str[];
int space=0;//calculate the space
str="who are you".toCharArray();
//System.out.println(str.length);
/*
* the fist scan,wo should find the sum of space
*/
int strlength=str.length;
for(int i=0;i<strlength;i++){
if(str[i]==' '){
space++;
}
}
/*
* two pointer,fisrt is the tail of old str
* second is the tail of new str
* the length of new str is old length + space *2
*/
int strtail=str.length-1;
int aftertail=str.length-1+space*2;
char newstr[]=new char[aftertail+1];
while(strtail>=0){
//if tailone is not space,then char is put the new position
if(str[strtail]!=' '){
newstr[aftertail--]=str[strtail--];
//else,wo should add %20 in it
}else{
strtail--;
newstr[aftertail--]='0';
newstr[aftertail--]='2';
newstr[aftertail--]='%';
}
}
for(int i=0;i<newstr.length;i++){
System.out.println(newstr[i]);
}
}
}