Check If Second String Is Rotation of Another String

Check if two strings are rotationally equal to each other

Your solution does not work because you calculate shift incorrectly, here is how you can fix it:

function areRotEq (str1, str2) {
var shift = null;
let i = 0;
for(char of str1){
if(!shift) shift = str2.indexOf(char);
else {
const currentShift = Math.abs(str2.indexOf(char) - i);
if (shift != currentShift) return false;
}
i++;
}
return true;
}

Here is concatenation trick solution:

function areRotEq (str1, str2) {
if (str1.length != str2.length) return false;
return (str1 + str1).indexOf(str2) != -1;
}

Check if a string is rotation of another WITHOUT concatenating

One simple solution is by concatenating them and checking if the other one is a substring of the concatenated version.

I assume you mean concatenate the first string with itself, then check if the other one is a substring of that concatenation.

That will work, and in fact can be done without any concatenation at all. Just use any string searching algorithm to search for the second string in the first, and when you reach the end, loop back to the beginning.

For instance, using Boyer-Moore the overall algorithm would be O(n).

Interview question: Check if one string is a rotation of other string

First make sure s1 and s2 are of the same length. Then check to see if s2 is a substring of s1 concatenated with s1:

algorithm checkRotation(string s1, string s2) 
if( len(s1) != len(s2))
return false
if( substring(s2,concat(s1,s1))
return true
return false
end

In Java:

boolean isRotation(String s1,String s2) {
return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}

PHP - Check if a string is a rotation of another string

I would go for something like this:

function isSubstring($s1, $s2)
{
// If the strings match exactly then no need to proceed
if($s1 === $s2)
{
echo "it is!";
return;
}
elseif(strlen($s1) !== strlen($s2))
{
// Strings must be of equal length or else no need to proceed
echo "nope";
return;
}

// Put each character into an array
$s1 = str_split($s1);
$s2 = str_split($s2);

// Sort alphabetically based on value
sort($s1);
sort($s2);

// Triple check the arrays against one-another
if($s1 === $s2)
{
echo "it is!";
}
else
{
echo "nope";
}
}


Related Topics



Leave a reply



Submit