diff --git a/src/main/java/com/github/dkoval/leetcode/challenge/RotateString.java b/src/main/java/com/github/dkoval/leetcode/challenge/RotateString.java index 24d8fc0f..d2a88464 100644 --- a/src/main/java/com/github/dkoval/leetcode/challenge/RotateString.java +++ b/src/main/java/com/github/dkoval/leetcode/challenge/RotateString.java @@ -40,4 +40,26 @@ public boolean rotateString(String s, String goal) { return false; } } + + class RotateStringRev2 implements RotateString { + + @Override + public boolean rotateString(String s, String goal) { + int n = s.length(); + + if (n != goal.length()) { + return false; + } + + String ss = s + s; + + // try every possible starting position of ss + for (int i = 0; i < n; i++) { + if (ss.substring(i, i + n).equals(goal)) { + return true; + } + } + return false; + } + } } diff --git a/src/test/kotlin/com/github/dkoval/leetcode/challenge/RotateStringTest.kt b/src/test/kotlin/com/github/dkoval/leetcode/challenge/RotateStringTest.kt index ff2707d0..8e848ccb 100644 --- a/src/test/kotlin/com/github/dkoval/leetcode/challenge/RotateStringTest.kt +++ b/src/test/kotlin/com/github/dkoval/leetcode/challenge/RotateStringTest.kt @@ -1,6 +1,7 @@ package com.github.dkoval.leetcode.challenge import com.github.dkoval.leetcode.challenge.RotateString.RotateStringRev1 +import com.github.dkoval.leetcode.challenge.RotateString.RotateStringRev2 import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Nested import org.junit.jupiter.api.extension.ExtensionContext @@ -33,6 +34,20 @@ internal class RotateStringTest { RotateStringRev1().test(s, goal, expected) } } + + @Nested + inner class RotateStringRev2Test { + + @ParameterizedTest + @ArgumentsSource(InputArgumentsProvider::class) + fun `should return true if and only if s can become goal after some number of shifts on s`( + s: String, + goal: String, + expected: Boolean + ) { + RotateStringRev2().test(s, goal, expected) + } + } } private fun RotateString.test(s: String, goal: String, expected: Boolean) {