Sword Finger Offer 5: Replace Spaces

Keywords: Java

Please implement a function that replaces each space in a string with "% 20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

1. For this kind of array replication problem, we mainly deal with it from the back to the front.

2.Java to write is best handled by StringBuilder plus reverse.toString

3.2 pointers, p1 pointer to the end of the original array, P2 pointer to the end of the newly copied array. When p1 is not empty, p1 copies to p2. At the same time, p1 -, P2 -, when p1 points to empty, P2 continuously fills in the required value. At the same time, P2 decreases the corresponding number of times, p1 -.

package com.hnist.lzn.jinazhioffer;

public class TIhuanBlock {

    char[] RepalceBlank(char[] string,int length){

            if(string==null||length<=0){

                return null;
            }

            int originLength=0;
            int numberOfBlank = 0;
            int i = 0;
            //The last Java array is not'0'
            while(i<length){

                //Scan size
                ++originLength;
                if(string[i]==' '){

                    ++numberOfBlank;
                }

                ++i;

            }
            //Why is *2?
            int newLength = originLength+numberOfBlank*3;
            //And why?
            if(newLength<length)
                return null;

            //Sufficient number of new
            char[] strings = new char[newLength];

            //Prevent cross-border
            int indexOfOriginal = originLength-1;
            int indexOfNew = newLength-1;

            while(indexOfOriginal>=0&&indexOfNew>indexOfOriginal){

                if(string[indexOfOriginal]==' '){

                    strings[indexOfNew--]='0';
                    strings[indexOfNew--]='2';
                    strings[indexOfNew--]='%';

                }else{

                    strings[indexOfNew--] = string[indexOfOriginal];
                }

                --indexOfOriginal;

            }

           return strings;

    }

    public static void main(String[] args) {

            String nums = "we are happy";

            char[] string = nums.toCharArray();

           char[] strings =  new TIhuanBlock().RepalceBlank(string,string.length);

            for(int i=0;i<strings.length;i++){

                System.out.print(strings[i]);
            }

    }
}

 

Posted by stirton on Mon, 15 Apr 2019 21:33:32 -0700