The sword refers to Offer - replace the space

Topic description: Please implement a function that replaces each space in a string with "%20".

Analysis: First, convert the string into a character array, and then replace it. However, in C#, once the array is initialized, the size of the storage space cannot be changed, so I used two character arrays. Then how to replace it? After scanning the space, move the following characters backward, and then replace, so the time complexity is O(n^2). Is there a method with O(n) time complexity? We can try to scan from the back to the front. First scan it to get the number of spaces, and then allocate the space, adding twice the number of spaces to the original space, which is the space after the space is replaced. Then scan from back to front, using two pointers indexNew, indexCurrent, indexNew points to the end of the new character array, indexCurrent points to the end of the original character array, if a space is encountered, replace it, if not, move the character to the position of indexNew.

code show as below:

private static string ReplaceSpace(string str)
        {
            if (str == null || str=="")
                return "-1";
            string result = null;
            char[] charStr = str.ToArray(); //The input string is converted into an array
            int originalLen = charStr.Length;
            int newLen = originalLen;
            //get the number of spaces
            for (int i=0;i<originalLen;i++)
            {
                if (charStr[i] == ' ')
                    newLen += 2;
            }
            char[] newChar = new char[newLen]; // new string array
            for(int i=originalLen-1;i>=0;)
            {
                if(charStr[i]!=' ')
                {
                    newChar[newLen - 1] = charStr[i];
                    newLen--;
                }
                //replace spaces
                else
                {
                    newChar [newLen - 1] = '0';
                    newChar [newLen - 2] = '2';
                    newChar [newLen - 3] = '%';
                    newLen -= 3;
                }
                i--;
            }
            result = new string(newChar);
            return result;
        }
Summary: Because two string arrays are newly declared, and the space complexity is O(n), the idea is relatively simple.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326659381&siteId=291194637