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);
    }

}
相关推荐
武哥聊编程几秒前
【从0带做】基于Springboot3+Vue3的生态养殖管理系统
java·学习·vue·毕业设计·springboot
隔山打牛牛1 分钟前
如何实现jvm中自定义加载器?
java
by__csdn1 分钟前
JavaScript性能优化实战:异步与延迟加载全方位攻略
开发语言·前端·javascript·vue.js·react.js·typescript·ecmascript
阿里嘎多学长2 分钟前
2025-12-11 GitHub 热点项目精选
开发语言·程序员·github·代码托管
牛三金3 分钟前
魔改-隐语PSI通信,支持外部通信自定义
服务器·前端·算法
菜鸟233号3 分钟前
力扣106 从中序与后序遍历序列构造二叉树 java实现
java·算法·leetcode
杨超越luckly4 分钟前
HTML应用指南:利用GET请求获取全国瑞思教育门店位置信息
前端·python·arcgis·html·门店数据
尘缘浮梦6 分钟前
chrome英文翻译插件
前端·chrome
HIT_Weston7 分钟前
58、【Ubuntu】【Gitlab】拉出内网 Web 服务:Gitlab 配置审视(二)
前端·ubuntu·gitlab
YJlio7 分钟前
Active Directory 工具学习笔记(10.11):AdRestore 实战脚本与命令速查——从事故回滚到合规留痕
java·笔记·学习