The URL is changed

The URL. Write a method to replace all Spaces in a string with %20. Assume that there is enough space at the end of the string for new characters and that you know the “real” length of the string. (Note: If implemented in Java, use character arrays to operate directly on arrays.)

Example 1:

Input: “Mr John Smith “, 13 Output: “Mr %20John%20Smith “Example 2:

Input: “, 5 Output: “%20%20%20%20%20” hint:

The value is in the range of 0, 500000.

java

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)); }}returnsb.toString(); }}Copy the code

python

class Solution(object) :
    def replaceSpaces(self, S, length) :
        
        tmp=[]
        for i in range(length):
            if S[i:i+1] = ="":
                tmp.append("% 20")
            else:
                tmp.append(S[i:i+1])
        res = ' '.join(tmp)
        return res
Copy the code

The idea is to iterate, check if it’s a space, insert %20 if it is