Skip to content

Instantly share code, notes, and snippets.

@leonw007
Created April 5, 2015 22: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 leonw007/ca1cbd10288a9facf2c6 to your computer and use it in GitHub Desktop.
Save leonw007/ca1cbd10288a9facf2c6 to your computer and use it in GitHub Desktop.
cc150-1.4
package ch1;
/*
1.4 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.)
* The core condition is that we have sufficient space at the end.
* if we don't care about space, we can just create a new space for new char array.
* In our case, we want to minimize the pace usage, so we start to assign values from the end of the char array
* first, calculate how much space we need according to the number of space
* second, assign new value to the same string from the end, becasue we have many space at the end and we only need
* this one char array in this case.
Time Complexity O(n) Space O(1)
*/
public class ReplaceSpace {
public static String replace(String arg, int length) {
char[] cha = arg.toCharArray();
int countSpace=0;
int newLength;
for(int i=0; i<length; i++) {
if(cha[i]==' ') {
countSpace++;
}
}
newLength = length + 2*countSpace;
int j = length-1;
for(int i=newLength-1;i>=0;i--){
if(cha[j] != ' ') {
cha[i]=cha[j];
}else {
cha[i]='0';
cha[i-1]='2';
cha[i-2]='%';
i = i-2;
}
j--;
}
arg= new String(cha);
return arg;
}
public static void main(String[] args) {
String a = "I am so strong ";
// char[] cha = a.toCharArray();
// a =cha.toString();
System.out.println(replace(a, 14));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment