URL化
难度:
标签:
题目描述
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)
Example 1:
Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith"
Example 2:
Input: " ", 5 Output: "%20%20%20%20%20"
Note:
0 <= S.length <= 500000
代码结果
运行时间: 32 ms, 内存: 22.3 MB
/*
* 题目思路:
* 1. 使用Java Stream来操作字符串。
* 2. 用String的chars()方法转为IntStream并处理空格替换。
* 3. 使用Collectors.joining()将流结果连接成最终字符串。
*/
import java.util.stream.Collectors;
public class URLifyStream {
public static String replaceSpaces(String s, int trueLength) {
return s.substring(0, trueLength)
.chars()
.mapToObj(c -> c == ' ' ? "%20" : String.valueOf((char)c))
.collect(Collectors.joining());
}
public static void main(String[] args) {
String str = "Mr John Smith ";
int trueLength = 13;
String result = replaceSpaces(str, trueLength);
System.out.println(result);
}
}
解释
方法:
该题解采用了直接操作字符串的方法。首先,通过截取输入字符串直到给定的“真实”长度,以去除尾部可能的空白或额外空间。然后,使用字符串的replace方法,将截取后的字符串中的所有空格字符替换为'%20'。这种方法简洁且直接,便于理解和实现。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
这种方法中,如果输入字符串的真实长度指的是字符串尾部之前的长度,那么在什么情况下会出现截取后仍有尾部空白的情况?
▷🦆
在执行`replace`方法之前进行字符串截取的原因是什么?是否可以在不截取的情况下直接替换然后截取?
▷🦆
该算法的时间复杂度是多少?字符串的截取和替换操作是否会影响效率?
▷