LeetCode Python 796 Rotate String

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
  • A是个小陀螺,最大的爱好就是不停地把最左边的元素移到最右边。现在问:A在不停变身的时候有没有可能变成B?
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

  • 最常规最朴素的思路就是完全实现A的华丽变身过程,collections模块中的deque可以帮忙实现这一变态行径:
    • deque(maxlen=N)创建一个长度为N的固定队列的双向队列。
      • 队列满时在此端添加n个值会同时删除彼端的n个值。
      • maxlen一经设定不能修改。
      • rotate(m):正值时右侧m个元素移至左侧,负值相反。
      • len(d)=d.maxlen时,开始达到上限,增加会导致另一侧的删除。
      • extendleft()把其中的元素逐个相加到左侧。
>>> 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就会不停地旋转,每次对比即可。

  • 但是,有一种更赛艇的思路:

    • 如果A能美少女变身成B,说明:
      • 若把A首尾相接成为一个环a,把B首尾相接成为一个环b。
      • 环a和环b就是相等的。
    • 但是当场将A或者B放进一个链表是件很烦人的事情,所以应该曲线救国。
      • A:雪菜碧池
      • B:碧池雪菜
      • BB:碧池雪菜碧池雪菜
      • 假设A将头部的N个元素移到尾部变成了B,那么,把两个B组成字符串蜈蚣,在2B拼接处就是完整的A。
      • 所以,更偷懒的答案是:
return len(B)==len(A) and A in B+B

猜你喜欢

转载自blog.csdn.net/weixin_41084236/article/details/81219107
今日推荐