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.
Output: true
Explanation: letter 'e' and 'g' in string
Output: false
Explanation: letter 'f' in string
Contents
Solution using HashMap, store mapping from both strings Solution using an array, store mapping from both strings
In this approach, we are going to store mapping from characters in
- We are making sure that order is preserved.
- No two characters map to the same character
For example, consider
- Base for the solution is, both strings should have same length, if not we can
-
In the first step, we map letter
p froms to lettert fromt and mapt fromt top froms .Mapping from s to t Letters from 's' Letters from 't' e a Mapping from t to s Letters from 't' Letters from 's' a e -
In the second step, we map letter
g froms to letterd fromt and mapd fromt tog froms .Mapping from s to t Letters from 's' Letters from 't' e a g d Mapping from t to s Letters from 't' Letters from 's' a e d g -
In the third step, we map letter
g froms , but it already present in the map, so we can skip this. -
Since we are able to add mapping from
s tot andt tos with same characters, so we can return true.
Implementation
-
We will create a function
usingHashMapStoreMapping that takes input arguments strings andt . -
Base case is, if the length of
s is not equal tot , then we can simply returnfalse . -
We will create two
HashMaps to store characters mapping froms tot andt tos -
Then, we will loop through characters from string
s and add to map and at the same time add characters mapping fromt tos . If mapping of characters are same in both maps are same, then the strings are isomorphic otherwise not.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n) since we are storing the mapping into a
In this approach, we are going to implement the solution same as above, instead of using a
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1) since we are storing the mapping into an array of fixed size of 128.
Above implementations source code can be found at