[Sword pointing to offer|2. Replace spaces]

0.Replace spaces

image-20230408125524652
Insert image description here

Double pointer:

In the C language version of the function prototype, since the formal parameter is a character pointer, the actual parameter must be a character array name. The array name is the address of the first element of the array. With the address of the first element of the array, you can change any one of the character arrays. The value of the element, but note: out-of-bounds access to the array is not allowed here, that is, if there is no extra space for you to access, you cannot "self-expand" (actually an out-of-bounds access). For the function prototype provided by Likuan, because there is no extra space, an additional space can only be opened to complete it, and this space can only be opened on the heap;

However, the C language version of the function prototype on Niuke.com has a second parameter, which shows that this string can be accommodated, so it will not be accessed out of bounds.

Pay attention to distinguishing the difference between the function prototypes given by Likou and Niuke, I fell into the trap!

image-20230408143617667image-20230408143701660

Through this question, I found that I have a deeper understanding of the function prototype given in the OJ question, including reducing the dimensionality of the array name passed parameter into a pointer, and whether it is a problem of the return stack space address.

1.C language version

char* replaceSpace(char* s){
    int len=0,count=0;
    for(int i=0;s[i]!='\0';i++)
    {
        len++;
        if(s[i]==' ') count++;
    }

    int newEnd=len+2*count;
    int oldEnd=len;

    char* ret=(char*)malloc(sizeof(char)*(newEnd+1));
    int retLen=newEnd+1;
    
    while(oldEnd>=0)//这里因为不是原地修改,当newEnd==oldEnd的时候还得继续移
    {
        if(s[oldEnd]!=' ')
        {
            ret[newEnd--]=s[oldEnd--];
        }
        else
        {
            ret[newEnd--]='0';
            ret[newEnd--]='2';
            ret[newEnd--]='%';
            oldEnd--;
        }
    }
    return ret;
}

2.C++ version

class Solution {
public:
    string replaceSpace(string s) {
        int count=0;
        int oldLen=s.size();
        for(int i=0;s[i]!='\0';i++)
        {
            if(s[i]==' ') count++;
        }
        s.resize(s.size()+2*count);
        int newLen=s.size();

        while(oldLen>=0&&newLen>oldLen)//这里因为是原地修改,当newEnd==oldEnd的时候可以不用移动了
        {
            if(s[oldLen]!=' ')
            {
                s[newLen--]=s[oldLen];
            }
            else
            {
                s[newLen--]='0';
                s[newLen--]='2';
                s[newLen--]='%';
            }
            --oldLen;
        }
        return s;
    }

Guess you like

Origin blog.csdn.net/qq_64428099/article/details/130027626
Recommended