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

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

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

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

9 9<br />

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

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

Saved successfully!

Ooh no, something went wrong!