Algorithm


Problem Name: 796. Rotate String

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position.

  • For example, if s = "abcde", then it will be "bcdea" after one shift.

 

Example 1:

Input: s = "abcde", goal = "cdeab"
Output: true

Example 2:

Input: s = "abcde", goal = "abced"
Output: false

 

Constraints:

  • 1 <= s.length, goal.length <= 100
  • s and goal consist of lowercase English letters.
 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public boolean rotateString(String A, String B) {
    return A.length() == B.length() && (A + A).indexOf(B) != -1;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "abcde", goal = "cdeab"

Output

x
+
cmd
true

#2 Code Example with Javascript Programming

Code - Javascript Programming


const rotateString = function(A, B) {
  if (A.length != B.length) return false;
  return A.concat(A).includes(B);
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "abcde", goal = "cdeab"

Output

x
+
cmd
true

#3 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0796_RotateString
    {
        public bool RotateString(string A, string B)
        {
            if (A.Length != B.Length) return false;
            if (A.Length  <  2) return true;

            var shifts = new int[A.Length + 1];
            for (int i = 0; i  < = A.Length; i++)
                shifts[i] = 1;
            for (int left = -1, right = 0; right  <  A.Length; left++, right++)
            {
                while (left >= 0 && A[left] != A[right])
                    left -= shifts[left];
                shifts[right + 1] = right - left;
            }

            var index = 0;
            foreach (var ch in A + A)
            {
                while (index >= 0 && B[index] != ch)
                    index -= shifts[index];
                index++;
                if (index == A.Length) return true;
            }

            return false;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "abcde", goal = "abced"

Output

x
+
cmd
false
Advertisements

Demonstration


Previous
#795 Leetcode Number of Subarrays with Bounded Maximum Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#797 Leetcode All Paths From Source to Target Solution in C, C++, Java, JavaScript, Python, C# Leetcode