Skip to content

Instantly share code, notes, and snippets.

@marlonklc
Last active January 14, 2020 13:44
Show Gist options
  • Save marlonklc/fd249d5db464720a38b93092010fdf2f to your computer and use it in GitHub Desktop.
Save marlonklc/fd249d5db464720a38b93092010fdf2f to your computer and use it in GitHub Desktop.
[CHALLENGE]: String rotation
- 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
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);
}
}
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