The LeetCode problem 796 - “Rotate String” is defined as follows:
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.
s and goal?
s and goal?
s or goal can be empty?
s and goal must have at least one character.s and goal will be of equal length?
s and goal can have different lengths.To solve this problem, the main idea is to check if goal can be obtained by rotating s. If two strings are of different lengths, they cannot be rotations of each other. Otherwise, we can concatenate s with itself (i.e., s + s), and check if goal is a substring of this concatenated string.
This works because concatenating s with itself essentially covers all possible rotations within its structure. For example, for s = 'abcde', concatenating it with itself gives 'abcdeabcde'. The goal string needs to be a substring of this new string to be a valid rotation.
#include <string>
class Solution {
public:
bool rotateString(std::string s, std::string goal) {
if (s.length() != goal.length()) {
return false;
}
std::string concatenated = s + s;
return (concatenated.find(goal) != std::string::npos);
}
};
s and goal are different. If they are, return false since they cannot be rotations of each other.s with itself to cover all possible rotations.find function to check if goal is a substring of the concatenated string.s.
find function in the standard library.This efficient approach ensures that the problem is solved within acceptable limits for given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?