[LeetCode] Challenge log 796

797. Rotate String

Use hash function to compare if B is a “rotate string” of A


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.

1
2
3
4
5
6
7
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.

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if A == '' and B == '': return True
A2 = A + A
n = len(A)
shift = set()
for i in range(n):
shift.add(A2[i:i + n])
if B in shift:
return True
else:
shift.remove(A2[i:i + n])
return False
0%