The Indian Engineer

Problem 796 Rotate String

Posted on Last edited 3 mins

String

Problem Statement

Link - Problem 796

Question

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.

Example 1

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

Example 2

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

Constraints

Solution

class Solution {
public:
    bool rotateString(string s, string goal) {
        if(s.size()!=goal.size())
            return false;

        string test = s+s;
        int t = test.size(), g = goal.size();
        int j;
        for(int i=0; i<t-g; i++){
            j = 0;
            while(j<g && test[i+j] == goal[j]){
                j++;
            }
            if(j==g)
                return true;
        }

        return false;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
String matching O(n^2) O(1)

Explanation

1. Intuition

2. Implementation

A neat trick to find all the rotations of a string is to concatenate the string with itself and then find all the substrings of size n where n is the size of the original string.