当前位置:网站首页>Sword finger offer 05 Replace spaces

Sword finger offer 05 Replace spaces

2022-07-05 08:21:00 Programmer Xiao Li

subject :

Please implement a function , Put the string s Replace each space in with "%20".

Example 1:

Input :s = "We are happy."
Output :"We%20are%20happy."

Limit :

0 <= s The length of <= 10000

Ideas :

1. Go through the first time , Check the number of spaces , Spaces need to be replaced with “%20”, Therefore, the array needs to be expanded .array.length - count + count * 3 Is the size of the array after replacement .

2. Copy from front to back .

class Solution {
    public String replaceSpace(String s) {
        if (s == null){
            return null;
        }

        char[] array = s.toCharArray();
        int count = 0;
        for (char c : array){
            if (c == ' '){
                count++;
            }
        }

        char[] newArray = new char[array.length - count + count * 3];
        int pointer = newArray.length - 1;
        for (int j = array.length - 1; j >= 0; j--){
            if (array[j] != ' '){
                newArray[pointer--] = array[j];
                continue;
            }
            newArray[pointer--] = '0';
            newArray[pointer--] = '2';
            newArray[pointer--] = '%';
        }

        return new String(newArray);
    }
}

 

原网站

版权声明
本文为[Programmer Xiao Li]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050816402866.html