4. Replace spaces

  Question : Please implement a function that replaces each space in a string with "%20". For example, input "We are happy" and output "We%20are%20happy".

  Ideas :

  1. First calculate the total length of the new array. Since the space is replaced with "%20", each space will have two extra characters. So new length = original length + number of spaces * 2.
  2. Prepare two pointers P1, P2. P1 points to the end of the original string and P2 points to the end of the new string.
  3. Next, move the pointer P1 forward, and copy the characters pointed to by it to the position pointed to by P2 one by one, until the first space is encountered. After hitting the first space, move P1 forward 1 space and insert the string "%20" before P2. Since the length of "%20" is 3, it is also necessary to move P2 forward by 3 spaces.
  4. Repeat the 3 steps, when P1 and P2 point to the same position, it means that all spaces have been replaced. All characters are copied (moved) only once, so the time complexity is O(n).

 

  Test cases :
  
  1. The input string contains spaces (the spaces are at the front, the back, and the middle of the string, and there are multiple spaces in a row)
  2. There are no spaces in the input string.
  3. Special input test (the string is a NULL pointer, the string is an empty string, the string has only one space character, and there are only multiple consecutive spaces in the string).

  Code :

#include<iostream>
#include<cstring>
using namespace std;

//length 为字符数组 string的总容量
void ReplaceBlank(char string[], int length)
{
    if (string == NULL || length <= 0)
    {
        return;
    }

    //originalLength为字符串string的实际长度
    int originalLength = 0;
    int numberOfBlank = 0;
    int i = 0;
    while(string[i] != '\0')
    {
        ++originalLength;

        if (string[i] == ' ')
        {
            ++numberOfBlank;
        }

        ++i;
    }

    //newLength为替换空格之后新的长度
    int newLength = originalLength + numberOfBlank * 2;
    if (newLength > length)
    {
        return;
    }

    int indexOfOriginal = originalLength;  //指针P1
    int indexOfNew = newLength;            //指针P2
    while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
    {
        if (string[indexOfOriginal] == ' ')
        {
            string[indexOfNew--] = '0';
            string[indexOfNew--] = '2';
            string[indexOfNew--] = '%';
        }
        else
        {
            string[indexOfNew--] = string[indexOfOriginal];
        }

        --indexOfOriginal;
    }

}

void Test(char str[], int length, char expected[])
{
    ReplaceBlank(str, length);

    if(expected == NULL && str == NULL)
        cout << "passed" << endl;
    else if(expected == NULL && str != NULL)
        cout << "failed" << endl;
    else if(strcmp(str, expected) == 0)
        cout << "passed" << endl;
    else
        cout << "failed" << endl;
}


void Test1()
{
    const int length = 100;

    char str[length] = "hello world";
    Test(str, length, "hello%20world");
}

void Test2()
{
    const int length = 100;

    char str[length] = "helloworld";
    Test(str, length, "helloworld");
}

//空指针
void Test3()
{
    Test(NULL, 0, NULL);
}

//空字符串
void Test4()
{
    const int length = 100;

    char str[length] = "";
    Test(str, length, "");
}

int main()
{
    Test1();
    Test2();
    Test3();
    Test4();

    return 0;
}

 

Related topics:

  There are two sorted arrays A1 and A2, and there is enough free space at the end of A1 to accommodate A2. Please implement a function that inserts all numbers in A2 into A1 and all numbers are sorted.

Method: Compare the numbers in A1 and A2 from the end of the cutter head, and copy the larger number to the appropriate position in A1.

learn by analogy:

When merging two arrays (including strings), if copying each number (or character) from front to back requires repeated moves, then we can consider copying from back to front, which can reduce the number of moves and improve efficiency .

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325187625&siteId=291194637