Description:
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = ‘abcde’, then it will be ‘bcdea’ after one shift on A. Return True if and only if A can become B after some number of shifts on A.
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
Note:
- A and B will have length at most 100.
题意:定义对字符串的一次shift为——将字符串最左端的字符与最右端的字符交换位置;现在,给定两个字符串A与B,计算是否可以通过对A进行多次的shift得到字符串B;
解法:要使得A可以通过多次的shift得到字符串B,那么在A中一定可以找到一个位置,从当前位置循环遍历字符串的长度得到的结果就是字符串B;因此,我们只需要遍历字符串A,每次碰到与字符B.charAt(0)相同的字符时,我们进行上述的处理,判断是否可以得到字符串B;
Java
class Solution {
public boolean rotateString(String A, String B) {
if (A.length() != B.length()) return false;
if (A.length() == 0 && B.length() == 0) return true;
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) != B.charAt(0)) continue;
int index = i;
boolean right = true;
for (int j = 0; j < B.length(); j++) {
if (A.charAt(index % A.length()) != B.charAt(j)) {
right = false;
break;
}
index++;
}
if (index - i == B.length() && right) {
return true;
}
}
return false;
}
}