[leetcode] 796. Rotate String @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88778402

原题

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.

解法

遍历A, 如果某个字符与B的首字符相等, 尝试将A重构成B, 如果重构成功,则返回True.
Time: O(n)
Space: O(n)

代码

class Solution(object):
    def rotateString(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        # base case
        if A == B: return True
        # A takes some shift
        for i, char in enumerate(A):
            if char == B[0]:
                # try to reconstruct B
                left, right = A[:i], A[i:]
                if right + left == B:
                    return True
        return False

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88778402
今日推荐