面试题 01.03.URL化
题目描述
URL化。编写一种方法,将字符串中的空格全部替换为%20
。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1
输入:"Mr John Smith ", 13
输出:“Mr%20John%20Smith”
示例2
输入:" “, 5
输出:”%20%20%20%20%20"
提示
- 字符串长度在 [0, 500000] 范围内。
- 需要知道有多少个空格
- 从尾到头来修改字符串更为方便
示例代码
Java 新建字符数组
public class Question01_03{
public static void main(String[] args) {
String one = "Mr John Smith";
String two = " ";
Solution s = new Solution();
System.out.println(s.replaceSpaces(one, 13));
System.out.println(s.replaceSpaces(two,5));
}
}
class Solution{
public String replaceSpaces(String S,int length) {
char chars[] = S.toCharArray();
char newchars[] = new char[length*3];
int index = 0;
int n = chars.length;
for(int i = 0;i < length;i++) {
if(chars[i] == ' ') {
newchars[index] = '%';
newchars[index+1] = '2';
newchars[index+2] = '0';
index += 3;
}else
newchars[index++] = chars[i];
}
return new String(newchars,0,index);
}
}
Java 提交结果
执行用时:9 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:46.9 MB, 在所有 Java 提交中击败了35.44% 的用户
示例代码
Java 原地修改
public class Question01_03{
public static void main(String[] args) {
String one = "Mr John Smith ";
String two = " ";
Solution s = new Solution();
System.out.println(s.replaceSpaces(one, 13));
System.out.println(s.replaceSpaces(two,5));
}
}
class Solution{
public String replaceSpaces(String S, int length) {
char[] chars = S.toCharArray();
int index = chars.length - 1;
for (int i = length - 1; i >= 0; i--) {
if (chars[i] == ' ') {
chars[index] = '0';
chars[index - 1] = '2';
chars[index - 2] = '%';
index -= 3;
} else {
chars[index] = chars[i];
index--;
}
}
return new String(chars, index + 1, chars.length - index - 1);
}
}
Java 提交结果
执行用时:9 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:45.2 MB, 在所有 Java 提交中击败了99.72% 的用户