"Sword refers to offer" 04: Replace spaces


❝
你自己的代码如果超过6个月不看,再看的时候也一样像是别人写的。—— 小浩

❞

Replace spaces


Title description

Please implement a function to replace every space in a string with %20. For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.

Original title display

"Sword refers to offer" 04: Replace spaces

solution

Solution 1:
Create StringBuilder, traverse the original string, and directly append to StringBuilder when encountering non-spaces, and append %20 to StringBuilder when encountering spaces.


public class Solution {
    /**
     * 将字符串中的所有空格替换为%20
     * @param str 字符串
     * @return 替换后的字符串
     */
    public String replaceSpace(StringBuffer str) {
        if (str == null || str.length() == 0) {
            return str.toString();
        }
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; ++i) {
            char ch = str.charAt(i);
            sb.append(ch == ' ' ? "%20" : ch);
        }

        return sb.toString();
    }
}

Solution 2 [Recommendation]
First traverse the original string, and if a space is encountered, append any two characters, such as two spaces, at the end of the original string.

Use the pointer p to point to the end of the original string, q point to the end of the current string, p, q traverse from back to front, when p encounters a space, the position of q should be appended '02%' in turn, if it is not a space, directly append the point pointed to by p character.

❝
思路扩展:在合并两个数组(包括字符串)时,如果从前往后复制每个数字(或字符)需要重复移动数字(或字符)多次,那么我们可以考虑从后往前复制,这样就能减少移动的次数,从而提高效率。

❞
public class Solution {
    /**
     * 将字符串中的所有空格替换为%20
     * @param str 字符串
     * @return 替换后的字符串
     */
    public String replaceSpace(StringBuffer str) {
        if (str == null || str.length() == 0) {
            return str.toString();
        }

        int len = str.length();
        for (int i = 0; i < len; ++i) {
            if (str.charAt(i) == ' ') {
                // append 两个空格
                str.append("  ");
            }
        }

        // p 指向原字符串末尾
        int p = len - 1;

        // q 指向现字符串末尾
        int q = str.length() - 1;

        while (p >= 0) {
            char ch = str.charAt(p--);
            if (ch == ' ') {
                str.setCharAt(q--, '0');
                str.setCharAt(q--, '2');
                str.setCharAt(q--, '%');
            } else {
                str.setCharAt(q--, ch);
            }
        }

        return str.toString();

    }
}

Test case

  1. The input string contains spaces (the space is at the first/last/middle of the string; the string has multiple consecutive spaces);
  2. There are no spaces in the input string;
  3. Special input test (string is a null pointer; string is an empty string; string has only one space character; there are multiple consecutive spaces in the string).

    Test site for this question

    "Sword refers to offer" 04: Replace spaces

I organized all the solutions I wrote into an e-book on github, and hit the top of the github rankings in three days! Nearly 5w people downloaded and read! If you want to get it, just enter the link below (remember to give me a star) :

https://github.com/geekxh/hello-algorithm
"Sword refers to offer" 04: Replace spaces

Guess you like

Origin blog.51cto.com/15076236/2609617