796. Rotate String #783
-
Topics: Given two strings A shift on
Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can take advantage of the properties of string concatenation. Specifically, if we concatenate the string Let's implement this solution in PHP: 796. Rotate String <?php
/**
* @param String $s
* @param String $goal
* @return Boolean
*/
function rotateString($s, $goal) {
// Check if lengths are equal; if not, return false
if (strlen($s) !== strlen($goal)) {
return false;
}
// Concatenate s with itself
$doubleS = $s . $s;
// Check if goal is a substring of doubleS
return strpos($doubleS, $goal) !== false;
}
// Example usage:
$s1 = "abcde";
$goal1 = "cdeab";
var_dump(rotateString($s1, $goal1)); // Output: true
$s2 = "abcde";
$goal2 = "abced";
var_dump(rotateString($s2, $goal2)); // Output: false
?> Explanation:
Complexity:
This solution efficiently determines if one string can become another through rotations. |
Beta Was this translation helpful? Give feedback.
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 ofs
will appear as substrings within that concatenated string. This allows us to simply check ifgoal
is a substring ofs + s
.Let's implement this solution in PHP: 796. Rotate String