25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

1 4 Write a method to decide if two strings are anagrams or not<br />

SOLUTION<br />

There are two easy ways to solve this problem:<br />

Solution #1: Sort <strong>the</strong> strings<br />

1 boolean anagram(String s, String t) {<br />

2 return sort(s) == sort(t);<br />

3 }<br />

Solution #2: Check if <strong>the</strong> two strings have identical counts for each unique char.<br />

9 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures<br />

pg 48<br />

1 public static boolean anagram(String s, String t) {<br />

2 if (s.length() != t.length()) return false;<br />

3 int[] letters = new int[256];<br />

4 int num_unique_chars = 0;<br />

5 int num_completed_t = 0;<br />

6 char[] s_array = s.toCharArray();<br />

7 for (char c : s_array) { // count number of each char in s.<br />

8 if (letters[c] == 0) ++num_unique_chars;<br />

9 ++letters[c];<br />

10 }<br />

11 for (int i = 0; i < t.length(); ++i) {<br />

12 int c = (int) t.charAt(i);<br />

13 if (letters[c] == 0) { // Found more of char c in t than in s.<br />

14 return false;<br />

15 }<br />

16 --letters[c];<br />

17 if (letters[c] == 0) {<br />

18 ++num_completed_t;<br />

19 if (num_completed_t == num_unique_chars) {<br />

20 // it’s a match if t has been processed completely<br />

21 return i == t.length() - 1;<br />

22 }<br />

23 }<br />

24 }<br />

25 return false;<br />

26 }

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

Saved successfully!

Ooh no, something went wrong!