Skip to content

Commit

Permalink
Improved solution to "Rotate String" problem
Browse files Browse the repository at this point in the history
  • Loading branch information
dkoval committed Nov 3, 2024
1 parent 49b39d9 commit e3a4682
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit e3a4682

Please sign in to comment.