【Sword Finger Offer】 —— Replace space

Topic requirements

Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy. The string after replacement is We% 20Are% 20Happy.

analysis

Method 1:
Analyze this question carefully. The idea that popped up in our mind is to traverse the string from front to back, and replace the characters when encountering spaces. When replacing, move the following characters back.
This time complexity is high, reaching O (n ^ 2). If the title requires us to replace the original string, and the input string has enough free memory behind it, the problem can be solved in this way.

Method two:
But let's think about how to solve this problem by traversing from back to front to find spaces to replace.
It is still a way to analyze the concrete words of abstract concepts.
In the string We Are Happy. Contains / 0, we find that there are 14 and there are two spaces.
First, we first calculate the number of bytes required after replacement = 12 + 3 * 2 = 18
So, let p2 point to the end of the replaced string, p1 points to the end of the current string
Insert picture description here
and copy the contents of the string in turn, until the first a pointer to the first space across Insert picture description here
the space to replace the first 20%, p2 move forward three grid, a lattice p1 moves forward
Insert picture description here
sequentially copy the string of characters forward space until it hits
Insert picture description here
this time p1 , p2 points to the same position, indicating that all spaces have been replaced

Code

void RepalceBlank(char string[], int length)
{
    if (string == nullptr || length <= 0)
        return;
    int originalLength = 0;
    int originalBlank = 0;
    int i = 0;
    while (string[i] != '\0')
    {
        originalLength++;
        if (string[i] == ' ')
            originalBlank++;
        i++;
    }

    int newlength = originalLength + originalBlank * 2;
    if (newlength > length)//注意:originalLength才为实际的字符串长度,length为传入的字符串长度,当所要的空间都不够了肯定就退出了
        return;

    int p2 = newlength;
    int p1 = originalLength;//注意:originalLength才为实际的字符串长度,length为传入的字符串长度

    //不管p2是移动一格还是三格,p1都是移动一格
    while (p2 > p1&& p1 >= 0)
    {
        if (string[p1] == ' ')
        {
            string[p2--] = '0';
            string[p2--] = '2';
            string[p2--] = '%';
        }
        else
        {
            string[p2--] = string[p1];
        }
        p1--;
    }
}
Published 98 original articles · won praise 9 · views 3655

Guess you like

Origin blog.csdn.net/qq_43412060/article/details/105306767