Skip to content

Instantly share code, notes, and snippets.

@Soben
Created October 21, 2023 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Soben/5b27e7404ffbe68a79e2da5a24cca23d to your computer and use it in GitHub Desktop.
Save Soben/5b27e7404ffbe68a79e2da5a24cca23d to your computer and use it in GitHub Desktop.
Cassidoo | isIsomorphic String

Solution to Cassidoo's Week of October 15, 2023 Challenge

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if there is a one-to-one mapping possible for every character of the first string to every character of the second string.

My initial version would ignore any non-alphanumeric characters.

That said, this definitely does not handle accents, etc.

<?php
function isIsomorphic($original, $encrypted) {
$key = [];
$original = str_split($original);
$encrypted = str_split($encrypted);
if (count($original) != count($encrypted)) {
// every character MUST exist in both.
return false;
}
for ($i = 0; $i < count($original); $i++) {
if (!isset($key[$original[$i]])) {
$key[$original[$i]] = $encrypted[$i];
}
if ($key[$original[$i]] != $encrypted[$i]) {
return false;
}
}
return true;
}
// true
var_dump(isIsomorphic('abb', 'cdd'));
// false
var_dump(isIsomorphic('cassidy', '1234567'));
// true
var_dump(isIsomorphic('cass', '1233'));
// true
var_dump(isIsomorphic('elephant', 'aka0b1td'));
// false
var_dump(isIsomorphic('elephant', 'aka0b1td asd'));
// true
var_dump(isIsomorphic('an elephant', '1t aka0b1td'));
// false
var_dump(isIsomorphic('an elephant', '1taka 0b1td'));
// false
var_dump(isIsomorphic('an elephant', '3t aka0b1td'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment