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 9 | Sorting and Searching<br />

9 2 Write a method to sort an array of strings so that all <strong>the</strong> anagrams are next to each<br />

o<strong>the</strong>r<br />

SOLUTION<br />

CareerCup com<br />

pg 66<br />

The basic idea is to implement a normal sorting algorithm where you override <strong>the</strong> compareTo<br />

method to compare <strong>the</strong> “signature” of each string In this case, <strong>the</strong> signature is <strong>the</strong><br />

alphabetically sorted string<br />

1 public class AnagramComparator implements Comparator {<br />

2 public String sortChars(String s) {<br />

3 char[] content = s.toCharArray();<br />

4 Arrays.sort(content);<br />

5 return new String(content);<br />

6 }<br />

7<br />

8 public int compare(String s1, String s2) {<br />

9 return sortChars(s1).compareTo(sortChars(s2));<br />

10 }<br />

11 }<br />

Now, just sort <strong>the</strong> arrays, using this compareTo method instead of <strong>the</strong> usual one<br />

12 Arrays.sort(array, new AnagramComparator());<br />

1 8 0

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

Saved successfully!

Ooh no, something went wrong!