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.8 Assume you have a method isSubstring which checks if one word is a substring of<br />

ano<strong>the</strong>r. Given two strings, s1 <strong>and</strong> s2, write code to check if s2 is a rotation of s1 using<br />

only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).<br />

SOLUTION<br />

pg 48<br />

Just do <strong>the</strong> following checks<br />

1. Check if length(s1) == length(s2). If not, return false.<br />

2. Else, concatenate s1 with itself <strong>and</strong> see whe<strong>the</strong>r s2 is substring of <strong>the</strong> result.<br />

input: s1 = apple, s2 = pleap ==> apple is a substring of pleappleap<br />

input: s1 = apple, s2 = ppale ==> apple is not a substring of ppaleppale<br />

1 public static boolean isRotation(String s1, String s2) {<br />

2 int len = s1.length();<br />

3 /* check that s1 <strong>and</strong> s2 are equal length <strong>and</strong> not empty */<br />

4 if (len == s2.length() && len > 0) {<br />

5 /* concatenate s1 <strong>and</strong> s1 within new buffer */<br />

6 String s1s1 = s1 + s1;<br />

7 return isSubstring(s1s1, s2);<br />

8 }<br />

9 return false;<br />

10 }<br />

1 0 3<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!