每天一个算法练习之字符空格替换

题目示例:把字符串中的每个空格替换成“%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]);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值