String Rotation
Write a method to check if given a string (S1) there is a way to rotate it so it matches another given string.
What an efficient way of rotating:
String s1 = "erbottlewat"
// so we get S2
String s2 = "waterbottle"
Link here to the repo to solve the problem
ππ Tips
Remember that concatenating Strings is a very expensive process
Could you use a StringBuilder to optimise the time?
π Solution 1
This is a fairly easy question, an easy straightforward solution in O(N), would be to iterate from left to right - grabbing each initial letter as a pivot and appending it to the end of the StringBuilder, effectively moving one letter at the time until we see if one combination will match S2.
boolean solution(String s1, String s2) {
StringBuilder stringBuilder = new StringBuilder();
String placeHolder = s2;
for (int i = 0; i < s2.length(); i++) {
String left = placeHolder.substring(1);
char right = placeHolder.charAt(0);
stringBuilder.append(left);
stringBuilder.append(right);
placeHolder = stringBuilder.toString();
stringBuilder.delete(0, stringBuilder.length());
if (placeHolder.charAt(0) == s1.charAt(0) && placeHolder.equals(s1)) return true;
}
return false;
}
Question added by Diego Romero