Given a method isSubstring, two strings s1 and s2, check whether s1 is a rotation of s2 using only one call to isSubstring.
Any comments on the code below?
I would like to check the complexities as well:
For isSubstring
:
- runtime: \$O(n^2)\$
- memory: in place
For isRotation
:
- runtime: \$O(n^2)\$
- memory: \$O(n)\$
import static org.junit.Assert.*;
import org.junit.Test;
public class Solution {
// Find whether string s1 is a rotation of string s2
// using only one call to isSubstring
static boolean isSubstring(String s1, String s2) {
// return true if s1 is a substring of s2
// false otherwise
int n1 = s1.length();
int n2 = s2.length();
for (int i = 0; i < n2; i++) {
if (i+n1>n2){
return false;
}
else if (s1.equals(s2.substring(i,i+n1))) {
return true;
}
}
return false;
}
static boolean isRotation(String s1, String s2) {
// return true if s2 is a rotation of s1
// false otherwise
// concatenate all the rotated strings of s1
StringBuffer allRotated = new StringBuffer();
int n1 = s1.length();
int n2 = s2.length();
if (n1 != n2) {
return false;
}
allRotated.append(s1);
for (int i = n1 - 1; i > 0; i--) {
allRotated.append(s1.substring(i) + s1.substring(0, i));
}
// Return true if s2 is a substring of allRotated
String rotated = allRotated.toString();
return isSubstring(s2, rotated);
}
@Test
public static void abcTest() {
String abc = "abc";
String cab = "cab";
String bca = "bca";
assertTrue(isRotation(abc, cab));
assertTrue(isRotation(abc, bca));
}
@Test
public static void falseTest(){
String abc = "abc";
String cba = "cba";
assertFalse(isRotation(abc,cba));
}
@Test
public static void evenTest(){
String abcd = "abcd";
String dcba = "dcba";
assertFalse(isRotation(abcd,dcba));
}
@Test
public static void identityTest(){
String aaaa = "aaaa";
assertTrue(isRotation(aaaa,aaaa));
}
public static void main(String[] args) {
abcTest();
falseTest();
evenTest();
identityTest();
}
}
isSubstring
is O(n^2), what is n? If you append n strings of length n, how long is the whole string? Are you sureallRotated
needs to be that long? \$\endgroup\$