LeetCode - Algorithms - 796. Rotate String

Problem

796. Rotate String

Java

my solution - brute method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean rotateString(String A, String B) {
final int len_A = A.length();
final int len_B = B.length();
if (len_A != len_B)
return false;
if (A.isEmpty() && B.isEmpty())
return true;
for(int i=0; i<len_A; i++) {
A = A.substring(1)+A.charAt(0);
if (B.equals(A))
return true;
}
return false;
}
}

Submission Detail

  • 45 / 45 test cases passed.
  • Runtime: 5 ms, faster than 9.75% of Java online submissions for Rotate String.
  • Memory Usage: 38.4 MB, less than 32.29% of Java online submissions for Rotate String.

trick method

© 20+ basic Algorithms Problems from Coding Interviews 19. How to check if two String is rotations of each other?

There is a simple trick to solve this problem, just concatenate the String with itself and check if the rotation exists there. You can do that by using indexOf or substring method. If the concatenated String contains rotation then given String is a rotation of former.

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean rotateString(String A, String B) {
final int len_A = A.length();
final int len_B = B.length();
if (len_A != len_B)
return false;
String s = A + A;
return s.indexOf(B) != -1;
}
}

Submission Detail

  • 45 / 45 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate String.
  • Memory Usage: 37.2 MB, less than 75.85% of Java online submissions for Rotate String.