4. Replace space "to prove safety Offer" solution to a problem ----

topic

Please implement a function, each of the spaces in the replacement string as "20%."

You can assume that the maximum length of the input string is 1000.
Note that the output 1000 may be greater than the length of the string.

Sample
input: "We are happy."

Output: "We% 20are% 20happy."

Algorithm thinking

General idea is to traverse from front to back, all data after a space if they are, it will move two spaces, then set "20%." But it will because too much data to move to increase the number of time complexity.
CountOfBlank may first calculate the number of spaces to arrive at the new string length is n + 2 * countOfBlank, and then set the length of the string to the new length. Followed by moving the character, from the back Traversal string, characters are sequentially copied to the final position, encounter a space, filled with "20%."
Time complexity is O (n), n is the length of the string

Code

class Solution {
    public String replaceSpaces(StringBuffer str) {
        if (str == null) return null;

        int countOfBlank = 0;
        int oldLength = str.length();
        for(int i=0; i<str.length(); i++) {
            if (str.charAt(i) == ' ') countOfBlank++;
        }

        int newLength = str.length() + 2 * countOfBlank;
        str.setLength(newLength);
        int oldIndex = oldLength - 1;
        int newIndex = newLength - 1;
        //从后往前遍历
        while (oldIndex >= 0 && newIndex >= 0) {
            if (str.charAt(oldIndex) == ' ') {
                str.setCharAt(newIndex--, '0');
                str.setCharAt(newIndex--, '2');
                str.setCharAt(newIndex--, '%');
                 
            } else {
                str.setCharAt(newIndex, str.charAt(oldIndex));
                newIndex--;
            }
            oldIndex--;
        }

        return str.toString();
    }
}

Guess you like

Origin www.cnblogs.com/TatuCz/p/11115433.html