To prove safety: replace spaces

Title Description

Please implement a function, the replacement string into each space  "%20".

You can assume that the input string of maximum length  1000. Note that the length may be greater than the output string  1000.

Sample

输入:"We are happy."

输出:"We%20are%20happy."

solution

A Solution

It is replaced with a positive match.

String str = "We are happy.";
        
str = str == null?null : str.toString().replace(" ", "%20");
System.out.println(str);

 

Solution two

First traversal of the original string, calculates the number of spaces, the string length that is equal to the replaced original length plus 2 times the number of spaces.

Pointer  i points to the end of the original string, j points to the end now string ij forward traversal from when  i encountered space, j a position to be sequentially assigned  '0','2','%', then moving a i, j 3 move; if it is blank, direct assignment as a  i point of character.

Extended idea:

When merging two arrays (including string), if each of the digital copy from front to back (or characters) need to repeat the mobile digital (or characters) times, then we can consider copied from the back, so that movement can be reduced the number of times, thereby improving efficiency.

 

public  class Solution {
     public  static String replaceSpace (the StringBuffer STR) {
         int spacenum = 0; // spacenum to calculate the number of spaces 
        for ( int I = 0; I <str.length (); I ++ ) {
             IF (str.charAt (I ) == '' ) 
                spacenum ++ ; 
        } 
        int indexold = str.length () -. 1; // indexold str index is to replace the pre- 
        int newLength str.length = () + 2 * spacenum; // calculate space str length after conversion into 20% 
        int indexnew newLength = -. 1; // indexold of spaces is to replace str index after 20%
        str.setLength (newLength); // make the length of str expanded length after conversion to 20%, to prevent Subscript out of range 
        
        for (; indexold> = 0 && indexold <newLength; - indexold) {
             IF (str.charAt ( indexold) == '') { //
                 str.setCharAt (indexnew--, '0' ); 
                str.setCharAt (indexnew -, '2' ); 
                str.setCharAt (indexnew -, '%' ); 
            } the else { 
                str.setCharAt (indexnew - , str.charAt (indexold)); 
            } 
        } 
        return str.toString ();
    } 

    Public  static void main(String[] args) {
        String str = "We are happy.";
        StringBuffer s = new StringBuffer(str);
        String newstr = replaceSpace(s);
        System.out.println(newstr);
    }
}

 

Time complexity of O (n)

 

Guess you like

Origin www.cnblogs.com/lisen10/p/11041059.html