Rotate String

XXX.Rotate String

String
Simulation

Problem Statement:

Given two strings s and goal, return true if and only if goal is a rotation of s. A rotation means we can rearrange the characters of s by moving some number of characters from the start to the end, keeping their relative order.

Algorithm:

  1. Check if the lengths of s and goal are different. If so, return false.
  2. Concatenate s with itself to create a doubled string.
  3. Check if goal is a substring of the doubled string using the contains function or equivalent.

Complexity:

Time: O(n), where n is the length of s | Space: O(n) for creating the concatenated string.

Java Implementation:


public boolean rotateString(String s, String goal) {
    // Check if the lengths are different
    if (s.length() != goal.length()) return false;

    // Concatenate 's' with itself
    String doubledString = s + s;

    // Check if 'goal' is a substring of the doubled string
    return doubledString.contains(goal);
}
                

Python Implementation:


def rotateString(s, goal):
    # Check if lengths are different
    if len(s) != len(goal):
        return False

    # Concatenate s with itself and check if goal is a substring
    return goal in (s + s)
                

C++ Implementation:


bool rotateString(string s, string goal) {
    // Check if lengths are different
    if (s.length() != goal.length()) return false;

    // Concatenate s with itself and check if goal is a substring
    return (s + s).find(goal) != string::npos;
}
                
Previous
Previous

Robot Room Cleaner

Next
Next

reorganize String