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

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 />

CareerCup.com<br />

1 8 0

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

Saved successfully!

Ooh no, something went wrong!