Isomorphic Strings
Problem
Given two strings s
and t
, determine if they are isomorphic.
Two strings s
and t
are isomorphic if the characters in s
can be replaced to get t
.
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.
Constraints
1 <= s.length <= 5 * 104
t.length == s.length
s
andt
consist of any valid ascii character.
Solution
The problem Isomorphic Strings
can be solved using 2 hash maps, one to check if a certain character is mapped to multiple characters and another to check if a certain character is mapped from multiple characters.
Implementation
class Solution
{
public:
bool isIsomorphic(string s, string t)
{
char from[128], to[128];
memset(from, -1, 128);
memset(to, -1, 128);
for (int i = 0; i < s.length(); i++)
{
if (from[s[i]] == -1 && to[t[i]] == -1)
{
from[s[i]] = t[i];
to[t[i]] = s[i];
}
else if (from[s[i]] != t[i] || to[t[i]] != s[i])
return false;
}
return true;
}
};