Skip to content

Instantly share code, notes, and snippets.

@JamesJi9277
Created March 30, 2015 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesJi9277/e8fc2faa560ac2329eac to your computer and use it in GitHub Desktop.
Save JamesJi9277/e8fc2faa560ac2329eac to your computer and use it in GitHub Desktop.
1.4
//Write a method to replace all spaces in a string with '%20'
//Bacause the String in Java is immutable, so we will use characters array
public class Solution{
public void replaceSpace(char[] str, int length){
if(str == null || str.length == 0)
return;
int count =0;
for(int i = 0;i <str.length;i++)
{
if(str[i] == ' ')
count++;
}
int newLength = str.length + 2*count;
for(int i = str.length -1; i>=0;i--)
{
if(str[i] == ‘ ’)
{
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}
else
{
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment