替换空格

由于昨天刷完第一题花的时间太多了,没有刷够,今天补上来,一切为了部落(offer)!


题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

解题思路:
先将StringBuffer转换成char[],循环获得字符串中的空格数。
空格数为0时直接返回原字符串,如果字符串为空则返回空。
新建一个字符串数组,数组的大小为,源字符串长度+空格数*2。
新建两个指针,分别指向源数组最后一个字符和新字符数组最后一个字符。
开始循环获取元字符串中的字符,每获得一个字符就填充到新字符数组相应位置。
如果遇到空格,则在新字符数组中从后往前依次插入"02%",直到源字符串遍历完毕为止。

代码:

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	int srcLen = str.length();
	        int blankCount = 0;
	        char[] srcChars = str.toString().toCharArray();
	        for(int i = 0; i < srcLen; i++)
	        {
	            if(srcChars[i] == ' ')
	            {
	            	blankCount++;
	            }
	        }
	        
	        //不用进行替换的情况
	        if(blankCount == 0)
	        {
	        	return str.toString();
	        }
	        else if(blankCount < 0)
	        {
	        	return null;
	        }
	        
	        int targetLen = blankCount*2 + srcLen;
	        char[] targetChars = new char[targetLen];
	        
	        int srcPoint = srcLen-1;
	        int targetPoint = targetLen - 1;
	        
	        while(srcPoint >= 0){
	        	char temp = srcChars[srcPoint--];
	        	if(temp == ' ')
	        	{
	        		targetChars[targetPoint--] = '0';
	        		targetChars[targetPoint--] = '2';
	        		targetChars[targetPoint--] = '%';
	        	}
	        	else
	        	{
	        		targetChars[targetPoint--] = temp;
	        	}
	        }
	        
			return new String(targetChars);
        
    }
}

总结:
这道题相对比较简单,只要计算出新数组所需的大小,然后在依据规则依次将相应字符填入即可。不过我的实现还比较单薄,效率还不高,有待优化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值