题目地址
题目描述
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例 1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例 2:
输入:" ", 5
输出:"%20%20%20%20%20"
提示:
- 字符串长度在 [0, 500000] 范围内。
题解
1. 构建一个三倍长度的数组
- 构建一个原来长度三倍的数组
- 遍历原字符串,遇到空格就转化为 20%
- 需要记录最终的位置,因为被替换的字符串长度不一定是原字符串的长度
代码如下:
class Solution {
public String replaceSpaces(String S, int length) {
if (S == null || S.length() == 0) {
return S;
}
if (length == 0) {
return "";
}
char[] charArray = S.toCharArray();
char[] targetArray = new char[length * 3];
int j = 0;
for (int i = 0; i < length; i++) {
char c = charArray[i];
if (c == ' ') {
targetArray[j++] = '%';
targetArray[j++] = '2';
targetArray[j++] = '0';
} else {
targetArray[j++] = c;
}
}
return new String(targetArray, 0, j);
}
}
时间复杂度为 O(n)
空间复杂度为 O(3*n)
2. 先遍历原字符串,确定最终的长度
- 先遍历原字符串,计算出空格的数量
- 最终字符串的长度为
最终长度 = 原长度 + 2 * 空格数量
代码如下:
class Solution {
public String replaceSpaces(String S, int length) {
if (S == null || S.length() == 0) {
return S;
}
if (length == 0) {
return "";
}
char[] charArray = S.toCharArray();
int whiteSpaceCount = 0;
for (int i = 0; i < length; i++) {
char c = charArray[i];
if (c == ' ') {
whiteSpaceCount++;
}
}
int targetLength = whiteSpaceCount * 2 + length;
char[] targetArray = new char[targetLength];
int j = 0;
for (int i = 0; i < length; i++) {
char c = charArray[i];
if (c == ' ') {
targetArray[j++] = '%';
targetArray[j++] = '2';
targetArray[j++] = '0';
} else {
targetArray[j++] = c;
}
}
return new String(targetArray);
}
}
时间复杂度为 O(n)
空间复杂度为 O(n + 2 * m)