27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

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

5. String with non-contiguous duplicate, e.g.: abababa<br />

Algorithm—With Additional Memory of Constant Size<br />

1 public static void removeDuplicatesEff(char[] str) {<br />

2 if (str == null) return;<br />

3 int len = str.length;<br />

4 if (len < 2) return;<br />

5 boolean[] hit = new boolean[256];<br />

6 for (int i = 0; i < 256; ++i) {<br />

7 hit[i] = false;<br />

8 }<br />

9 hit[str[0]] = true;<br />

10 int tail = 1;<br />

11 for (int i = 1; i < len; ++i) {<br />

12 if (!hit[str[i]]) {<br />

13 str[tail] = str[i];<br />

14 ++tail;<br />

15 hit[str[i]] = true;<br />

16 }<br />

17 }<br />

18 str[tail] = 0;<br />

19 }<br />

Test Cases:<br />

1. String does not contain any duplicates, e.g.: abcd<br />

2. String contains all duplicates, e.g.: aaaa<br />

3. Null string<br />

4. Empty string<br />

5. String with all continuous duplicates, e.g.: aaabbb<br />

6. String with non-contiguous duplicates, e.g.: abababa<br />

CareerCup.com<br />

9 8

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

Saved successfully!

Ooh no, something went wrong!