Leetcode 205. Isomorphic Strings
The problem “Isomorphic Strings” can be found at LeetCode (problem 205). Here’s the problem statement:
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.
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
Note: You may assume both s
and t
have the same length.
To determine if two strings s
and t
are isomorphic, we will:
s
to characters in t
, and from characters in t
to characters in s
.(s_char, t_char)
:
s_char
is already mapped to some character in t
, we check if it is mapped to t_char
.t_char
is already mapped to some character in s
, we check if it is mapped to s_char
.false
.true
.Here is the C++ implementation of the approach discussed:
#include <unordered_map>
#include <string>
class Solution {
public:
bool isIsomorphic(std::string s, std::string t) {
if (s.length() != t.length()) return false;
std::unordered_map<char, char> s_to_t;
std::unordered_map<char, char> t_to_s;
for (size_t i = 0; i < s.length(); ++i) {
char s_char = s[i];
char t_char = t[i];
// Check mapping from s to t
if (s_to_t.find(s_char) != s_to_t.end()) {
if (s_to_t[s_char] != t_char) {
return false;
}
} else {
s_to_t[s_char] = t_char;
}
// Check mapping from t to s
if (t_to_s.find(t_char) != t_to_s.end()) {
if (t_to_s[t_char] != s_char) {
return false;
}
} else {
t_to_s[t_char] = s_char;
}
}
return true;
}
};
The time complexity of this solution is O(n), where n is the length of the strings s
and t
. This is because we iterate over each character in the strings exactly once, and all operations within the loop (hash map operations) are O(1) on average.
The space complexity is also O(n) due to the storage used by the two hash maps that map characters from s
to t
and from t
to s
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?