Replace spaces---StringBuilder

Question: Replace spaces

Please implement a function to replace each space in the string s with "%20".

Example 1 :

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

limit:

0 <= length of s <= 10000

Java StringBuffer 和 StringBuilder 类

  • When modifying a string, you need to use the StringBuffer and StringBuilder classes. Unlike the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times, and it does not generate new unused objects. Because StringBuilder
    has a speed advantage compared to StringBuffer , it is recommended to use StringBuilder class in most cases. However, when the application requires thread safety, you must use StringBuffer class.

Problem-solving ideas:

  • 1. Use StringBuilder (fast) to use character arrays, first convert the string to a character array through the s.toCharArray() method, and then judge each character in the character array. When the character is empty, set'%20' 'String append to StringBuilder, otherwise append the original character to StringBuilder, and finally use the toString method to return the string representation of the data in this sequence.

  • 2. Using the auxiliary character array (small memory consumption), first define a character array whose length is 3 times the length of the string, and then traverse the characters at the index from 0 to length()-1 in the string (using the charAt() method), Then judge whether the character is empty. If it is empty, store the three characters %, 2, 0 in the character array in turn, otherwise, store the original character in the character array, and finally convert the character array to a string and return.

Implementation code:

class Solution{
    
    
    //方法一
    public String replaceSpace(String s) {
    
    
        StringBuilder res = new StringBuilder();
        for (Character c : s.toCharArray()) {
    
    
            if (c == ' ') {
    
    
                res.append("%20");
            } else {
    
    
                res.append(c);
            }
        }
        return res.toString();
    }
    //方法二
    public String replaceSpace2(String s) {
    
    
        int n = s.length();
        char[] array = new char[3 * n];
        int size = 0;
        for (int i = 0; i < n; i++) {
    
    
            char c = s.charAt(i);
            if (c == ' ') {
    
    
                array[size++] = '%';
                array[size++] = '2';
                array[size++] = '0';
            } else {
    
    
                array[size++] = c;
            }
        }
        String s1 = new String(array, 0, size);
        return s1;
    }
}

Guess you like

Origin blog.csdn.net/qq_33626996/article/details/111226196