[Offer] [5] [Replace Spaces]

Keywords: PHP Java

Topic Description

Implement a function that replaces each space in the string with "% 20".
For example, enter "We are happy." and output "We% 20 are% 20 happy.".

Thought analysis

  1. Character substitution in Java can be implemented using String's built-in function replaceAll
  2. Consider not using functions in Java: According to the parameters defined in the functions in the Niuhaiwan Exercise Questions are StringBuffer, and the return value is String.
  3. The whole idea is to first calculate the length of the string after replacing the blank space, and set two indexes. The old index points to the end of the original string, and the new index points to the end of the string after the length is changed. The old index scans from back to front, assigning the value of the string to the new index position in turn. If encountering the blank space, the new index assigns the value of% 20 in turn, and continues to scan.

Java code

public class Offer005 {
    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("We are no happy");
        System.out.println(Offer005.replaceSpace(str));

    }
    public static String replaceSpace(StringBuffer str) {
        return Solution2(str);
    }
    private static String Solution1(StringBuffer str) {
        if (str == null) {
            throw new IllegalArgumentException("invalid parameter!");
        }
        int length = str.length();
        int indexOfOrig = length - 1;// The old index position points to the end of the old string
        // Gets the total length of the replacement space
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ') {
                length += 2; // Because the space should be replaced by "% 20", the length of each space should be increased by 2.
            }
        }
        str.setLength(length);// Set the new str length
        int indexOfNew = length - 1;// The new index position points to the end of the new string
        while (indexOfNew > indexOfOrig) {
            if (str.charAt(indexOfOrig) != ' ') {
                str.setCharAt(indexOfNew--, str.charAt(indexOfOrig));
            } else {
                str.setCharAt(indexOfNew--, '0');
                str.setCharAt(indexOfNew--, '2');
                str.setCharAt(indexOfNew--, '%');
            }
            indexOfOrig--;
        }
        return str.toString();
    }
    private static String Solution2(StringBuffer str) {
        return str.toString().replaceAll(" ", "%20");
    }
}

Code Links

Sword Finger Office Code - Java

Posted by jxrd on Wed, 09 Oct 2019 11:15:11 -0700