【leetcode】面试题 01.03. URL化

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

示例1:

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

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

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

题解:


class Solution {
    public String replaceSpaces(String S, int length) {
        if(length == 0 || S == null || S.length() == 0){
            return S;
        }

        char[] s = S.toCharArray();
        int spaceCount = 0;

        for(int i = 0; i < length; i++){
            if(s[i] == ' '){
                spaceCount ++;
            }
        }

        int totalLength = length + 2 * spaceCount;
        int tl = totalLength;
        for( int i=length -1 ; i >= 0; i--){
            if(s[i] == ' '){
                s[-- totalLength] = '0';
                s[ -- totalLength] = '2';
                s[-- totalLength] = '%';
            }else{
                s[-- totalLength] = s[i];
            }
        }
        // 这里在写的时候并没有到开始的位置。
        if(totalLength >= 0 ){
            return new String(s).substring(totalLength, tl);
        }
        return new String(s);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值