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

}
相关推荐
深念Y15 分钟前
我明白为什么B站没法在浏览器开直播了——Windows Chrome推流踩坑全记录
前端·chrome·webrtc·浏览器·srs·直播·flv
言之。24 分钟前
【Python】免费的中文 AI 配音方案
开发语言·人工智能·python
zhangxingchao26 分钟前
AI应用开发七:可以替代 RAG 的技术
前端·人工智能·后端
天天进步201541 分钟前
Python全栈项目:从零手操一个高性能 API 网关
开发语言·python
Sun@happy42 分钟前
现代 Web 前端渗透——基础篇(1)
前端·web安全
Java面试题总结43 分钟前
java高频面试题(2026最新)
java·开发语言·jvm·数据库·spring·缓存
希冀1231 小时前
【CSS学习第十一篇】
前端·css·学习
苦逼的猿宝1 小时前
学生心理咨询评估系统
java·毕业设计·springboot·计算机毕业设计
隔窗听雨眠1 小时前
doctype、charset、meta如何控制整个渲染流水线
java·服务器·前端
kyriewen1 小时前
写组件文档写到吐?我用AI自动生成Storybook,同事以后直接抄
前端·javascript·面试