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:
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A)!=len(B):
return False
if len(A)==0:
return True
deq=collections.deque(A,maxlen=len(A))
deqb=collections.deque(B,maxlen=len(B))
for i in range(len(A)):
if deq==deqb:
return True
deq.rotate(1)
return False
>>> from collections import deque
>>> q=deque('我爸爸是刘备',maxlen=6)
>>> q
deque(['我', '爸', '爸', '是', '刘', '备'], maxlen=6)
>>> q.append('!')
>>> q
deque(['爸', '爸', '是', '刘', '备', '!'], maxlen=6)
>>> q.rotate(4)
>>> q
deque(['是', '刘', '备', '!', '爸', '爸'], maxlen=6)
>>> q.appendleft('我')
>>> q
deque(['我', '是', '刘', '备', '!', '爸'], maxlen=6)
>>> q.extendleft('爸爸')
>>> q
deque(['爸', '爸', '我', '是', '刘', '备'], maxlen=6)
如此,只要按下按钮,用A构成的deque就会不停地旋转,每次对比即可。
但是,有一种更赛艇的思路:
return len(B)==len(A) and A in B+B