|
| 1 | +package crackingTheCodingInterview.chap1; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +/** |
| 6 | + * ### String Rotation: |
| 7 | + * Assume you have a method isSubstringwhich checks if one word is a substring of another. |
| 8 | + * Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring |
| 9 | + * (e.g.,"waterbottle" is a rotation of "erbottlewat"). |
| 10 | + */ |
| 11 | +public class StringRotation { |
| 12 | + // Test Driven Development by Aseem Jain |
| 13 | + @Test |
| 14 | + public void test() { |
| 15 | + |
| 16 | + assert solution1("waterbottle", "erbottlewat"); |
| 17 | + assert solution1("apple", "pleap"); |
| 18 | + assert !solution1("camera", "macera"); |
| 19 | + |
| 20 | + } |
| 21 | + |
| 22 | + // Basic solution |
| 23 | + private boolean solution1(String s1, String s2) { |
| 24 | + if (s1.length() != s2.length()) { |
| 25 | + return false; |
| 26 | + } |
| 27 | + |
| 28 | + String dobuleString = s1 + s1; |
| 29 | + // make sure s2 is part of s1 |
| 30 | + return dobuleString.contains(s2); |
| 31 | + } |
| 32 | + |
| 33 | +} |
0 commit comments