URL化
1.题目要求
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例2
输入:" ", 5
输出:"%20%20%20%20%20"
提示:
字符串长度在 [0, 500000] 范围内。
2.解题思路
1.使用API。
2.循环数组,替换。
3.代码实现
实现1(使用API):
class Solution {
public String replaceSpaces(String S, int length) {
S = S.substring(0,length);
char[] ch = S.toCharArray();
S = S.replace(" ","%20");
System.out.print(S);
return S;
}
}
实现2:
class Solution {
public String replaceSpaces(String S, int length) {
char[] ch = S.toCharArray();
char[] temp = new char[length*3];
int f = 0;
int t = 0;
for( int i = 0; i < length; i++ ){
t = 2*f;
if( ch[i]!=' ' ){
temp[i+t]=ch[i];
} else{
temp[i+t] = '%';
temp[i+t+1] = '2';
temp[i+t+2] = '0';
f++;
}
}
String s = new String( temp ).trim();
return s;
}
}
4.总结
实现1
执行用时: 16 ms
内存消耗: 48.7 MB
实现2
执行用时: 12 ms
内存消耗: 49.3 MB