Skip to content

796. Rotate String

https://leetcode.com/problems/rotate-string/

js
/**
 * @param {string} A
 * @param {string} B
 * @return {boolean}
 */
var rotateString = function(A, B) {
  if (A.length !== B.length) {
    return false
  }

  if (!A && !B) {
    return true
  }

  for (let i = 0; i < A.length; i++) {
    if (A.slice(i) + A.slice(0, i) === B) {
      return true
    }
  }

  return false
}

/**
 * @param {string} A
 * @param {string} B
 * @return {boolean}
 */
var rotateString2 = function(A, B) {
  if (A.length !== B.length) {
    return false
  }

  return (A + A).indexOf(B) >= 0
}
py
class Solution:

    def rotateString(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        if len(A) != len(B):
            return False

        if not A:
            return True

        for i in range(len(A)):
            if A[i:] + A[0:i] == B:
                return True
        return False

    def rotateString2(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """
        if len(A) != len(B):
            return False
        return B in (A + A)