本题节选自leecode: 01.03. URL化:https://leetcode-cn.com/problems/string-to-url-lcci/
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例 1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例 2:
输入:" ", 5
输出:"%20%20%20%20%20"
提示:
字符串长度在 [0, 500000] 范围内。
--------------------------------------------------------------------------
算法题,读懂题意最重要。请充分下面理解黑体字部分。
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
题意应该是想让你在原字符数组做替换操作,算法感觉跟垃圾回收器的标记压缩算法有点类似,在同一空间下把数据迁移到空间另外一头再做操作。
人狠话不多,代码如下:
public class Solution {
public static void main(String[] args) {
Solution t = new Solution();
String result = t.replaceSpaces("Mr John Smith ", 13);
System.out.println("-->" + result + "<--");
result = t.replaceSpaces(" ", 5);
System.out.println("-->" + result + "<--");
result = t.replaceSpaces("assa ", 10);
System.out.println("-->" + result + "<--");
}
public String replaceSpaces(String S, int length) {
char[] str = S.toCharArray();
int i = length - 1, j = S.length() - 1;
while (i >= 0) {
if (str[i] == ' ') {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
} else {
str[j--] = str[i];
}
i--;
}
return String.valueOf(str, j + 1, S.length() - j - 1);
}
/**
*这个用例对示例是通过的,但是leecode显示超时,对于一些case不过关,必须按题意走啊
/
public String replaceSpaces_Bad(String S, int length) {
int i = S.indexOf(' ');
while (i < length) {
S = S.replaceFirst(" ", "%20");
length += 2;
i = S.indexOf(' ');
}
return S.substring(0, length);
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-url-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。