leetcode 796. Rotate String(python)
描述
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 进行 len(A) 次的 shift 操作,每次操作判断其与 B 是否相等,如果相等则返回 True, 如果遍历 len(A) 次之后仍不相等,则返回 False 。
解答
class Solution(object):
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
a = collections.Counter(A)
b = collections.Counter(B)
if a != b:
return False
n = len(A)
while n >= 0:
if A == B:
return True
else:
n -= 1
A = A[1:]+A[0]
return False
运行结果
Runtime: 16 ms, faster than 78.91% of Python online submissions for Rotate String.
Memory Usage: 13.7 MB, less than 10.19% of Python online submissions for Rotate String.
原题链接:leetcode.com/problems/ro…
您的支持是我最大的动力