Thursday, July 26, 2012

1.5 replaceSpace

Write a method to replace all spaces in a string with ‘%20’

Tough thing about this method will be how to replace a single char with 3 chars. We don't want to have to increase the array size everytime we hit a space because that wouldn't be very memory efficient. We want to increase the array size once and be done with it. Therefore, we want to find out how many spaces are there to begin with.

PsuedoCode


Now that we have the number of spaces, we need to increase the size of the array by 2*spaces. Next, we want to keep track of where we are in the old and new array. That way we can correctly put things from the old position to the new, adjusted position.

Lastly,we want to start from the back and move backwards. Because the back is filled with "null" chars, we won't lose any information.

No comments:

Post a Comment