Skip to content

796. Rotate String #783

Answered by mah-shamim
mah-shamim asked this question in Q&A
Nov 3, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

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

<?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
    r…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Nov 3, 2024
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Nov 3, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Nov 3, 2024
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants