Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a method to replace all spaces in a string with '%20'?

I have a question about a programming problem from the book Cracking The Code Interview by Gayl Laakmann McDowell, 5th Edition.

I'm not sure what is wrong with my answer? It varies a lot from the answer given in the book.

public String replace(String str){

   String[] words = str.split(" ");
   StringBuffer sentence = new StringBuffer();

   for(String w: words){
      sentence.append("%20");
      sentence.append(w);
   }

  return sentence.toString();
}
like image 636
Opal Avatar asked Dec 12 '22 02:12

Opal


1 Answers

Question in the book says:

Note: if implementing in Java, please use a character array so that you can perform this operation in place.

It also says that the char array that you get as input is long enough to hold the modified string.
By using split and StringBuffer you use additional O(n) space. That's why your answer varies a lot and is incorrect (apart from adding additional "%20").

like image 62
MD-11 Avatar answered Jan 11 '23 03:01

MD-11