LeetCode刷题笔记796:旋转字符串(Python实现)

给定两个字符串, A 和 B

A 的旋转操作就是将 A 最左边的字符移动到最右边。 例如, 若 A = 'abcde',在移动一次之后结果就是'bcdea' 。如果在若干次旋转操作之后,A 能变成B,那么返回True

示例 1:
输入: A = 'abcde', B = 'cdeab'
输出: true

示例 2:
输入: A = 'abcde', B = 'abced'
输出: false

注意:

  • A 和 B 长度不超过 100

Solution1:运用切片

class Solution(object):
    def rotateString(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        if A=="" and B=="":
            return True
        for i in range(len(A)):
            if A==B:
                return True
            else:
                A = A[1:] + A[0]
        return False

Solution2:一句代码...(可以看出Python强大之处,但是java也差不多)

class Solution(object):
    def rotateString(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        # A+A包含所有旋转之后的情况
        return len(A)==len(B) and B in A+A

 

你可能感兴趣的:(python,LeetCode)