leetcode 796. Rotate String (Python)

03 Jun 2020 Leetcode String

796. Rotate String (Python)

Related Topic

String.

Description

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.

Sample I/O

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.

Methodology

First We need to confirm that if case senstive matters, if blank space included. (Others like empty string, order and so on …)

Then if two strings length are equal return false; if two string are both empth return true

The brute force will be copy A to temp string and compare temp and B are same. If they are not same, we append the current character of A to temp string and iterate to next character of A.

However, the brute force is not efficent, the better way will be concatenate A and check if B in A+A, if B is rotate of A then B must be in A+A otherwise will be false.

Code

def rotateString(self, A: str, B: str) -> bool:
        return len(A) == len(B) and B in A + A

BigO

Iterate the element of the string once, so total time complexity is O(n)

Search

    Table of Contents