URL化 LeetCode day01

LeetCode URL化 打卡day01


```java
package com.stan.algo.leetcode;

public class URLReplaceSpaces {
    public static void main(String[] args) {
        System.out.println(replaceSpaces("Mr John Smith    ", 13));
        System.out.println(replaceSpaces("               ", 5));
    }
    /**
     * 输入:"Mr John Smith    ", 13
     * 输出:"Mr%20John%20Smith"
     * <p>
     * 输入:"               ",
     * 输出:"%20%20%20%20%20"
     *
     * @param S
     * @param length
     * @return
     */
    public static String replaceSpaces(String S, int length) {
        // 转为字符数组
        char[] chars = S.toCharArray();
        int count = 0;
        int i = 0;

        // 时间复杂度 O(n)
        for (; i < length; i++) {
            if (chars[i] != 32) {
                count++;
            }
        }


        char[] chars1;
        if (count == 0) {
            chars1 = new char[length * 3];
            for (int j = 0; j < length * 3; j++) {
                if (j % 3 == 0) {
                    chars1[j] = '%';
                } else if (j % 3 == 1) {
                    chars1[j] = '2';
                } else {
                    chars1[j] = '0';
                }

            }
            return new String(chars1);
        }
        chars1 = new char[3 * (length) - 2 * count];
        int index = 0;
        for (int j = 0; j < length; j++) {
            if (chars[j] == 32) {
                chars1[index++] = '%';
                chars1[index++] = '2';
                chars1[index++] = '0';
            } else {
                chars1[index] = chars[j];
                index++;
            }
        }

        return new String(chars1);
    }
}



![在这里插入图片描述](https://img-blog.csdnimg.cn/2021030910590694.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDEwOTcyNg==,size_16,color_FFFFFF,t_70#pic_center)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值