Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)
Example 1:
Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith" Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.
Example 2:
Input: " ", 5 Output: "%20%20%20%20%20"
Note:
0 <= S.length <= 500000
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
S = S[:length] if length < len(S) else S
return S.replace(' ', '%20')
class Solution {
public String replaceSpaces(String S, int length) {
char[] c = S.toCharArray();
int j = c.length;
for (int i = length - 1; i >= 0; i--) {
if (c[i] == ' ') {
c[--j] = '0';
c[--j] = '2';
c[--j] = '%';
} else {
c[--j] = c[i];
}
}
return new String(c, j, c.length - j);
}
}