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

}
相关推荐
自由随风飘8 小时前
python 题目练习1~5
开发语言·python
cynicme9 小时前
力扣3318——计算子数组的 x-sum I(偷懒版)
java·算法·leetcode
Bony-9 小时前
Go语言完全学习指南 - 从基础到精通------语言基础篇
服务器·开发语言·golang
青云交10 小时前
Java 大视界 -- Java 大数据在智能教育学习效果评估与教学质量改进实战
java·实时分析·生成式 ai·个性化教学·智能教育·学习效果评估·教学质量改进
崎岖Qiu10 小时前
【设计模式笔记17】:单例模式1-模式分析
java·笔记·单例模式·设计模式
fl17683111 小时前
基于python的天气预报系统设计和可视化数据分析源码+报告
开发语言·python·数据分析
Lei活在当下11 小时前
【现代 Android APP 架构】09. 聊一聊依赖注入在 Android 开发中的应用
java·架构·android jetpack
ACP广源盛1392462567311 小时前
(ACP广源盛)GSV6172---MIPI/LVDS 信号转换为 Type-C/DisplayPort 1.4/HDMI 2.0 并集成嵌入式 MCU
c语言·开发语言·单片机·嵌入式硬件·音视频
不穿格子的程序员11 小时前
从零开始刷算法-栈-括号匹配
java·开发语言·
漂流瓶jz11 小时前
Webpack中各种devtool配置的含义与SourceMap生成逻辑
前端·javascript·webpack