Title description:
Given two strings, A and B.
The rotation operation of A is to move the leftmost character of A to the rightmost. For example, if A ='abcde', the result will be'bcdea' after one move. If after several rotations, A can become B, then return True.
Example 1:
Input: A ='abcde', B ='cdeab'
Output: true
Example 2:
Input: A ='abcde', B ='abced'
Output: false
code show as below:
Method 1: Since A + A contains all the strings that can be obtained from A through the rotation operation, we only need to judge whether B is a substring of A + A.
class Solution {
public boolean rotateString(String A, String B) {
return A.length() == B.length() && (A + A).contains(B);
}
}
Method 2: Traverse after splicing.
class Solution {
public boolean rotateString(String A, String B) {
int n = A.length();
int m = B.length();
if (n == 0 && m == 0) {
return true;
}
if (n != m) {
return false;
}
for (int i = 0; i <= n; i++) {
StringBuilder builder = new StringBuilder();
builder.append(A, 1, n);
builder.append(A.charAt(0));
A = builder.toString();
//System.out.println(A);
if (A.equals(B)) {
return true;
}
}
return false;
}
}
Results of the: