lintcode-easy-Space Replacement

本文介绍了一种将字符串中的所有空格替换为%20的方法。该方法适用于字符数组形式的字符串,并假设数组有足够的空间进行替换操作。文章提供了一个Java实现示例,详细解释了如何计算空格数量并进行替换,最后返回替换后的字符串长度。

Write a method to replace all spaces in a string with%20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.

You code should also return the new length of the string after replacement.

Given "Mr John Smith", length = 13.

The string after replacement should be "Mr%20John%20Smith".

 

public class Solution {
    /**
     * @param string: An array of Char
     * @param length: The true length of the string
     * @return: The true length of new string
     */
    public int replaceBlank(char[] string, int length) {
        // Write your code here
        if(string == null || string.length == 0)
            return 0;
        
        int space_count = 0;
        int j = length - 1;
        
        while(j >= 0){
            if(string[j] == ' ')
                space_count++;
            j--;
        }
        
        int i = length + space_count * 2 - 1;
        
        for(j = length - 1; j >= 0; j--){
            if(string[j] == ' '){
                string[i--] = '0';
                string[i--] = '2';
                string[i--] = '%';
            }
            else{
                string[i--] = string[j];
            }
        }
        
        return length + space_count * 2;
    }
}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5249287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值