Monday, August 17, 2015

Strings replace spaces

Problem

Write a method to replace all spaces in a string with '%20'. You may assume that the
string has sufficient space at the end of the string to hold the additional characters,
and that you are given the "true" length of the string. (Note: if implementing in Java,
please use a character array so that you can perform this operation in place.)

Note: This is a problem from Cracking the Coding Interview Edition 5 Book.
Interesting part here: using Arrays.copy function

Solution

 private String replaceSpaces1(char[] s)
 {
  int count=0, i;
  int oldlen = s.length;

  for(i=0; i< oldlen; i++)
  {
   if(s[i] == ' ') count++;
  }


  int newlen = oldlen + count*2;
  s =  Arrays.copyOf(s, newlen);
  int pos = newlen-1;

  for(i= oldlen-1; i>= 0; i--)
  {
   if(s[i]==' ')
   {
    s[pos--] = '0';
    s[pos--] = '2';
    s[pos--] = '%';
   }
   else s[pos--] = s[i];
  }
  return Arrays.toString(s);
 }

No comments:

Post a Comment