剑指offer-4-替换空格-java

题目及测试

package sword004;
/*
 * 题目描述: 请实现一个函数,将字符串的每个空格替换为"%20"。
 * 例如输入"We are happy",则输出"We%20are%20happy."。
 */


public class main {
	
	public static void main(String[] args) {
		String [] testTable = {"hello","A man, a plan, a canal: Panama","av12,./34\\45"};
		for (String ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(String ito) {
		Solution solution = new Solution();
		String rtn;
		long begin = System.currentTimeMillis();
		System.out.print(ito);		    
		System.out.println();
		//开始时打印数组
		
		rtn= solution.replace(ito);//执行程序
		long end = System.currentTimeMillis();	
		
		System.out.println("rtn=" );
		System.out.print(rtn);
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功)

先计算input中空格的数目count,然后建立大小为length+2*count的新char数组,然后双指针遍历新旧数组,给新数组赋值,遇到旧数组的空格,就新数组设置3个值。

package sword004;

import java.util.Arrays;

public class Solution {
	public String replace(String input) {
		if(input == null) {
			return input;
		}
		int length = input.length();
		if(length ==0) {
			return input;
		}
		int count =0;
		for(int i=0;i<length;i++) {
			if(input.charAt(i) == ' ') {
				count++;
			}
		}
		if(count == 0) {
			return input;
		}
		int totalLength = length +2 * count;
		char[] array = new char[totalLength];
		int j = 0;
		for(int i=0;i<length;i++) {
			if(input.charAt(i) == ' ') {
				array[j++] = '%';
				array[j++] = '2';
				array[j++] = '0';
			}else {
				array[j++] = input.charAt(i);
			}
		}		
		return new String(array);
	}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值