796. Rotate String
Difficulty: Easy
Topics: String, String Matching
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:
Example 2:
Constraints:
Solution:
We can take advantage of the properties of string concatenation. Specifically, if we concatenate the string s with itself (i.e., s s), all possible rotations of s will appear as substrings within that concatenated string. This allows us to simply check if goal is a substring of s s.
Let's implement this solution in PHP: 796. Rotate String
Explanation:
Length Check: We first check if the lengths of s and goal are the same. If they are not, we immediately return false, as it's impossible for s to be transformed into goal.
Concatenation: We concatenate the string s with itself to create doubleS.
Substring Check: We use the strpos() function to check if goal exists as a substring in doubleS. If it does, we return true; otherwise, we return false.
Complexity:
This solution efficiently determines if one string can become another through rotations.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Rotate String. For more information, please follow other related articles on the PHP Chinese website!