Skip to content

Instantly share code, notes, and snippets.

@n2iw
Created April 3, 2015 04:58
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 n2iw/170195065cd5b257e4fd to your computer and use it in GitHub Desktop.
Save n2iw/170195065cd5b257e4fd to your computer and use it in GitHub Desktop.
/**
* 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.)
*
* EXAMPLE
* Input: "Mr John Smith"
* Output: "Mr%20Dohn%20Smith"
*
*
* @author james
*
*/
public class ReplaceSpace {
public static int solution(char[] str, int len) {
if (str == null || len == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < len; ++i) {
if (str[i] == ' ') {
++count;
}
}
int newLen = len + count * 2;
int newTail = newLen -1;
int oldTail = len -1;
while(newTail != oldTail) {
if (str[oldTail] == ' ') {
str[newTail--] = '0';
str[newTail--] = '2';
str[newTail--] = '%';
--oldTail;
} else {
str[newTail--] = str[oldTail--];
}
}
return newLen;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class TestReplaceSpace {
@Test
public void test() {
int newLen = ReplaceSpace.solution(null, 1);
assertEquals(newLen, 0);
newLen = ReplaceSpace.solution(null, 0);
assertEquals(newLen, 0);
testSolution("", 0);
testSolution(" ", 2);
testSolution(" ", 4);
testSolution("Hello world!", 2);
testSolution(" Hello world!", 4);
testSolution(" Hello world! ", 6);
testSolution("Hello,world!", 0);
}
private void testSolution(String s, int result) {
char[] str = new char[100];
for(int i = 0; i < s.length(); ++i) {
str[i] = s.charAt(i);
}
System.out.println("old: \"" + s + "\"");
assertEquals(ReplaceSpace.solution(str, s.length()), s.length() + result);
System.out.println("new: \"" + new String(str) + "\"");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment