力扣面试题 01.03. URL化

URL化

1.题目要求

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

示例1:

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

示例2

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

提示:

字符串长度在 [0, 500000] 范围内。

2.解题思路

1.使用API。
2.循环数组,替换。

3.代码实现

实现1(使用API):

class Solution {
    public String replaceSpaces(String S, int length) {
        S = S.substring(0,length);
        char[] ch = S.toCharArray();
        S = S.replace(" ","%20");
        System.out.print(S);
        return S;
    }
}

实现2:

class Solution {
    public String replaceSpaces(String S, int length) {
        char[] ch = S.toCharArray();
        char[] temp = new char[length*3];
        int f = 0;
        int t = 0;
        
        for( int i = 0; i < length; i++ ){
            t = 2*f;
            if( ch[i]!=' ' ){
                temp[i+t]=ch[i];

            } else{
                temp[i+t] = '%';
                temp[i+t+1] = '2';
                temp[i+t+2] = '0';
                f++;
            }
        }
        String s = new String( temp ).trim();
        return s;
    }
}

4.总结

实现1

执行用时: 16 ms
内存消耗: 48.7 MB

实现2

执行用时: 12 ms
内存消耗: 49.3 MB
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值