程序员面试金典 面试题 01.03.URL化

面试题 01.03.URL化

题目描述

URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)

示例1

输入:"Mr John Smith ", 13
输出:“Mr%20John%20Smith”

示例2

输入:" “, 5
输出:”%20%20%20%20%20"

提示
  • 字符串长度在 [0, 500000] 范围内。
  • 需要知道有多少个空格
  • 从尾到头来修改字符串更为方便
示例代码

Java 新建字符数组

public class Question01_03{
	public static void main(String[] args) {
		String one = "Mr John Smith";
		String two = "     ";
		Solution s = new Solution();
		System.out.println(s.replaceSpaces(one, 13));
		System.out.println(s.replaceSpaces(two,5));
	}
}

class Solution{
	public String replaceSpaces(String S,int length) {
		char chars[] = S.toCharArray();
		char newchars[] = new char[length*3];
		int index = 0;
		int n = chars.length;
		for(int i = 0;i < length;i++) {
			if(chars[i] == ' ') { 
				newchars[index] = '%';
				newchars[index+1] = '2';
				newchars[index+2] = '0';
				index += 3;
			}else 
				newchars[index++] = chars[i];
		}
		return new String(newchars,0,index);
	}
}

Java 提交结果
执行用时:9 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:46.9 MB, 在所有 Java 提交中击败了35.44% 的用户

示例代码

Java 原地修改

public class Question01_03{
	public static void main(String[] args) {
		String one = "Mr John Smith    ";
		String two = "               ";
		Solution s = new Solution();
		System.out.println(s.replaceSpaces(one, 13));
		System.out.println(s.replaceSpaces(two,5));
	}
}

class Solution{
	public String replaceSpaces(String S, int length) {
		char[] chars = S.toCharArray();
		int index = chars.length - 1;
		for (int i = length - 1; i >= 0; i--) {
			if (chars[i] == ' ') {
				chars[index] = '0';
				chars[index - 1] = '2';
				chars[index - 2] = '%';
				index -= 3;
			} else {
				chars[index] = chars[i];
				index--;
			}
		}
		return new String(chars, index + 1, chars.length - index - 1);
	}
}

Java 提交结果
执行用时:9 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:45.2 MB, 在所有 Java 提交中击败了99.72% 的用户

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W.Lionel.Esaka

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值