URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例2:
输入:" ", 5
输出:"%20%20%20%20%20"
//我的解决方案 (该方法执行时间太长)
//这样做是被题目固定了思路,下面的方法不使用数组性能就提升不少
class Solution {
public String replaceSpaces(String S, int length) {
char[] chars = new char[length];
chars = S.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (String.valueOf(chars[i]).equals(" ")) {
stringBuffer.append("%20");
} else {
stringBuffer.append(chars[i]);
}
}
return stringBuffer.toString();
}
}
class Solution {
public String replaceSpaces(String S, int length) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++){
if(S.charAt(i) == ‘ ‘){
sb.append("%20");
}else{
sb.append(S.charAt(i));
}
}
return sb.toString();
}
}
//这应该是最符合提议的
class Solution {
public String replaceSpaces(String S, int length) {
char[] s = S.toCharArray();
int j = S.length() - 1;
for (int i=length-1; i>=0; i--) {
if (s[i] == ‘ ‘) {
s[j--] = ‘0‘;
s[j--] = ‘2‘;
s[j--] = ‘%‘;
} else {
s[j--] = s[i];
}
}
return String.valueOf(s, j+1, S.length()-j-1);
}
}
class Solution {
public String replaceSpaces(String S, int length) {
char[] s = S.toCharArray();
int j = s.length;
for (int i=length-1; i>=0; i--) {
if (s[i] == ‘ ‘) {
s[--j] = ‘0‘;
s[--j] = ‘2‘;
s[--j] = ‘%‘;
} else {
s[--j] = s[i];
}
}
return new String(s, j, s.length-j);
}
}