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 小时前
IntelliJ IDEA中Spring Boot项目整合MyBatis:从零实现高效数据持久化
java·spring boot·intellij-idea·mybatis
雾月552 小时前
LeetCode 941 有效的山脉数组
java·开发语言·数据结构·算法·leetcode·职场和发展
晨曦5432103 小时前
函数和模式化——python
开发语言·python
leluckys4 小时前
swift-08-属性、汇编分析inout本质
开发语言·汇编·swift
百万蹄蹄向前冲4 小时前
三句话四分钟,豆包出题把吾秀
前端·人工智能·豆包marscode
小诸葛的博客4 小时前
Apache BookKeeper Ledger 的底层存储机制解析
java
半旧5184 小时前
重构谷粒商城11:node快速入门
java·前端·重构
嘤国大力士5 小时前
C++11&QT复习 (十六)
java·开发语言·c++