Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Last active August 29, 2015 14:03
Show Gist options
  • Save WOLOHAHA/26fbc68cfa7330acff52 to your computer and use it in GitHub Desktop.
Save WOLOHAHA/26fbc68cfa7330acff52 to your computer and use it in GitHub Desktop.
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.) EXAMPLE …
public class Main {
/**
* @* Runtime & space
* runtime: O(n)
* space: O(1)
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Main so = new Main();
String s="Mr John Smith ";
so.replaceSpaces(s.toCharArray(), 13);
}
public void replaceSpaces(char[] input, int trueLength){
if(input==null||trueLength==0||input.length==0)
return;
int count=0;
//first scan of the array: get the number of the spaces
for(int i=0;i<trueLength;i++){
if(input[i]==' ')
count++;
}
//2nd scan: start from the end to replace char[] in space.
int iLength=trueLength+2*count;
int p=iLength-1;
for(int i=trueLength-1;i>=0;i--){
if(input[i]==' '){
input[p--]='0';
input[p--]='2';
input[p--]='%';
}else{
input[p]=input[i];
p--;
}
}
System.out.println(new String(input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment