設計一種方法,將一個字符串中的所有空格替換成 %20 。你可以假設該字符串有足夠的空間來加入新的字符,且你得到的是“真實的”字符長度。
你的程序還需要返回被替換后的字符串的長度。
對于字符串"Mr John Smith", 長度為 13
替換空格之后,參數中的字符串需要變為"Mr%20John%20Smith",并且把新長度 17 作為結果返回。
**規則**
輸入:char[] 和int length
輸出:int 最新長度,從char[]取字符串
case:
```
數組為null
數組長度為0
"we are happy"
"we are "
"we are " --連續多個空格
" we are "
" we"
"we "
" we "
```
**思路**
1.創建一個新數組,然后一個拷貝過去,遇到空格替換為%20 復雜度為O(n)和O(n)
2.不創建新數組,創建新數組,遇到空格向后移動,復雜度為O(n^2)和O(1)
3.不創建新數組,先遍歷一遍,計算空格數量,然后兩個指針,從后向前拷貝,這樣復雜度為O(n)和O(1)
**代碼**
```
public int replaceBlank(char string[], int length) {
if(string == null) {
return 0;
}
if(length == 0) {
return 0;
}
int newLength = length;
for(int i = 0;i < length;i++) {
if(string[i] ==' ') {
newLength += 2;
}
}
if(newLength == length ) return length;
int p = length-1,q = newLength-1;
while(p>=0) {
if(string[p] == ' ') {
string [q--] = '0';
string [q--] = '2';
string [q--] = '%';
}else {
string[q--] = string[p];
}
p--;
}
return newLength;
}
```
測試代碼
```
public char[] fill(String cnt) {
char ret[] = new char[100];
char c[] = cnt.toarArray();
System.arraycopy(c, 0, ret, 0, c.length);
return ret;
}
public void assertString(String str) {
String str1 = str.replaceAll(" ","%20");
String str2 = replace(fill(str), str.length());
assertEquals(str1,str2);
}
public String replace(char arr[] ,int len) {
StringBlank1 m1 = new StringBlank1();
int newLen = m1.replaceBlank(arr, len);
if(arr == null) {
arr = new char[1];
}
return String.valueOf(arr, 0, newLen);
}
```