java面试题:简化URL

1 问题场景

编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的"真实"长度。

注意:字符串长度在 0, 500000 范围内。

2 答案

2.1 解决方案一

直接使用String方法解决

复制代码
    public static String replaceSpaces(String S, int length) {
        if(S.length()>500000||S.length()<0){
            return "字符长度超出合理范围";
        }
        S = S.substring(0,length).replace(" ","%20");
        return S;

    }

进行测试:

复制代码
package com.example.demo;

public class Solution {

    public static void main(String[] args) {
        System.out.println(replaceSpaces("               ",5));
    }

    public static String replaceSpaces(String S, int length) {
        if(S.length()>500000||S.length()<0){
            return "字符长度超出合理范围";
        }
        S = S.substring(0,length).replace(" ","%20");
        return S;

    }

}

2.2 解决方案二

复制代码
package com.example.demo;

public class Solution {

    public static void main(String[] args) {
        System.out.println(replaceSpaces("               ",5));
    }

    public static String replaceSpaces(String S, int trueLength) {
        if(S.length()>500000||S.length()<0){
            return "字符长度超出合理范围";
        }
        char[] str = S.toCharArray();
        int spaceCount = 0, index, i = 0;
        // 计算空格的数量
        for (i = 0; i < trueLength; i++) {
            if (str[i] == ' ') {
                spaceCount++;
            }
        }

        // 计算替换后的字符串长度
        index = trueLength + spaceCount * 2;
        // 计算替换后的字符串长度
        index = trueLength + spaceCount * 2;

        // 从后向前操作,进行替换
        if (trueLength < str.length) str[trueLength] = '\0'; // 标记实际结束位置
        for (i = trueLength - 1; i >= 0; i--) {
            if (str[i] == ' ') {
                str[index - 1] = '0';
                str[index - 2] = '2';
                str[index - 3] = '%';
                index = index - 3;
            } else {
                str[index - 1] = str[i];
                index--;
            }
        }
        return new String(str);
    }

}
相关推荐
挖掘狂人1 分钟前
如何设计一套秒杀系统?
java·后端·小程序·云开发
codigger8 分钟前
如何设计一套秒杀系统?
java·程序员·编程
Bczheng112 分钟前
浏览器访问本地html和服务器html的流程
前端
金八梭14 分钟前
格斗对决v4.5
前端·css·自动化·html·css3
狮子座的男孩17 分钟前
javascript 基础 es6:3、参数默认值,reset参数,spread扩展运算符,扩展运算符应用
前端·javascript·经验分享·es6·参数默认值·reset参数·spread扩展运算符
CodeSheep28 分钟前
华为园区,为啥碰到的高颜值妹子总是外包牌,华为工牌的基本都是资深大姐...
前端·后端·程序员
Rain的Java大神之路31 分钟前
Transformer 面试与 Java 落地:吃透 Self-Attention,从 QKV 公式到 KV Cache
java·后端·ai编程
map_3d_vis32 分钟前
JSAPI 4.0 的命名空间:BMap 和 BMapGL 为什么都能用
前端·javascript·typescript·百度地图
sharemylove33 分钟前
Java 常用类 学习笔记
java·开发语言·经验分享·笔记·学习
恋猫de小郭36 分钟前
Flutter HC 旋转 ANR,而且还和之前的 HCPP 问题类似
android·前端·flutter