205. Isomorphic Strings #111
-
Topics: Given two strings Two strings All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1:
Example 2:
Example 3:
Constraints:
Follow-up: Can you come up with an algorithm that is less than |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We can use two hash maps (or associative arrays in PHP) to track the mappings of characters from Let's implement this solution in PHP: 205. Isomorphic Strings <?php
function isIsomorphic($s, $t) {
if (strlen($s) != strlen($t)) {
return false;
}
$mapST = [];
$mapTS = [];
for ($i = 0; $i < strlen($s); $i++) {
$charS = $s[$i];
$charT = $t[$i];
// Check if there is a mapping for charS to charT
if (isset($mapST[$charS])) {
if ($mapST[$charS] != $charT) {
return false;
}
} else {
$mapST[$charS] = $charT;
}
// Check if there is a mapping for charT to charS
if (isset($mapTS[$charT])) {
if ($mapTS[$charT] != $charS) {
return false;
}
} else {
$mapTS[$charT] = $charS;
}
}
return true;
}
// Test cases
echo isIsomorphic("egg", "add") ? 'true' : 'false'; // Output: true
echo "\n";
echo isIsomorphic("foo", "bar") ? 'true' : 'false'; // Output: false
echo "\n";
echo isIsomorphic("paper", "title") ? 'true' : 'false'; // Output: true
?> Explanation:
This approach runs in O(n) time complexity, where n is the length of the strings, making it efficient for the input constraints. |
Beta Was this translation helpful? Give feedback.
We can use two hash maps (or associative arrays in PHP) to track the mappings of characters from
s
tot
and vice versa.Let's implement this solution in PHP: 205. Isomorphic Strings