796. Rotate String – Solution [Brute-Force to Best]

Here’s the question link on LeetCode 796. Rotate String:-

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

Optimal: Simulate Every Rotation

We can simply try every possible rotation of the string and check whether it matches goal.

  • First, check if both strings have the same length. If not, return false.
  • Rotate the string one position to the left.
  • Compare it with goal.
  • Repeat until we’ve tried all possible rotations.
class Solution {
public:
    bool rotateString(string s, string goal) {
        if(s.size() != goal.size())
            return false;

        for(int i = 0; i < s.size(); i++) {
            if(s == goal)
                return true;

            char first = s[0];
            s.erase(s.begin());
            s.push_back(first);
        }

        return false;
    }
};
796. Rotate String Optimal Solution

Leave a Reply