25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 1 | Arrays and Strings<br />

1 5 Write a method to replace all spaces in a string with ‘%20’<br />

SOLUTION<br />

The algorithm is as follows:<br />

1 Count <strong>the</strong> number of spaces during <strong>the</strong> first scan of <strong>the</strong> string<br />

2 Parse <strong>the</strong> string again from <strong>the</strong> end and for each character:<br />

» If a space is encountered, store “%20”<br />

» Else, store <strong>the</strong> character as it is in <strong>the</strong> newly shifted location<br />

1 public static void ReplaceFun(char[] str, int length) {<br />

2 int spaceCount = 0, newLength, i = 0;<br />

3 for (i = 0; i < length; i++) {<br />

4 if (str[i] == ‘ ‘) {<br />

5 spaceCount++;<br />

6 }<br />

7 }<br />

8 newLength = length + spaceCount * 2;<br />

9 str[newLength] = ‘\0’;<br />

10 for (i = length - 1; i >= 0; i--) {<br />

11 if (str[i] == ‘ ‘) {<br />

12 str[newLength - 1] = ‘0’;<br />

13 str[newLength - 2] = ‘2’;<br />

14 str[newLength - 3] = ‘%’;<br />

15 newLength = newLength - 3;<br />

16 } else {<br />

17 str[newLength - 1] = str[i];<br />

18 newLength = newLength - 1;<br />

19 }<br />

20 }<br />

21 }<br />

CareerCup com<br />

pg 48<br />

1 0 0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!