205. Isomorphic Strings
1. Description
Given two strings s and t, determine if they are isomorphic.
Two strings 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.
2. Example
Example 1:
Input: s = “egg”, t = “add”
Output: true
Example 2:
Input: s = “foo”, t = “bar”
Output: false
Example 3:
Input: s = “paper”, t = “title”
Output: true
3. Note
- You may assume both s and t have the same length.
4. Solutions
My Accepted Solution
n = s.size()
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
bool isIsomorphic(const string &s, const string &t) {
unordered_map<char, char> from_letter, to_letter;
for (int i = 0; i < s.size(); ++i) {
if (from_letter.find(s[i]) != from_letter.end() && from_letter[s[i]] != t[i] ||
to_letter.find(t[i]) != to_letter.end() && to_letter[t[i]] != s[i]) {
return false;
}
from_letter[s[i]] = t[i];
to_letter[t[i]] = s[i];
}
return true;
}
};