Last active
January 14, 2020 13:44
-
-
Save marlonklc/fd249d5db464720a38b93092010fdf2f to your computer and use it in GitHub Desktop.
[CHALLENGE]: String rotation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Write a func that accepts 2 strings, and returns true if one string is rotation of the other: | |
"abcde", "eabcd" - true | |
"abcde", "cdeab" - true | |
"abcde", "abced" - false | |
"abc", "a" - false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
public class StringRotationCompactCode { | |
@Test | |
public void test() { | |
System.err.println("abcde => eabcd: " + isRotation("abcde", "eabcd")); | |
System.err.println("abcde => cdeab: " + isRotation("abcde", "cdeab")); | |
System.err.println("abcde => abced: " + isRotation("abcde", "abced")); | |
System.err.println("abc => a: " + isRotation("abc", "a")); | |
} | |
private boolean isRotation(String str1, String str2) { | |
if (str1.length() != str2.length()) return false; | |
String str1Repeated = str1.concat(str1).concat(str1); | |
return str1Repeated.contains(str2); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
public class StringRotationMassiveCode { | |
@Test | |
public void test() { | |
System.err.println("abcde => eabcd: " + isRotation("abcde", "eabcd")); | |
System.err.println("abcde => cdeab: " + isRotation("abcde", "cdeab")); | |
System.err.println("abcde => abced: " + isRotation("abcde", "abced")); | |
System.err.println("abc => a: " + isRotation("abc", "a")); | |
} | |
private boolean isRotation(String str1, String str2) { | |
if (str1.length() != str2.length()) return false; | |
String str2Copy = str2; | |
for (int x = 1; x <= str1.length(); x++) { | |
char firstChar = str2Copy.charAt(0); | |
str2Copy = str2Copy.substring(1, str2.length()) + firstChar; | |
if (str2Copy.equals(str1)) return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment