Skip to content

Commit ff71752

Browse files
added isomorphic string question
1 parent f8da3bd commit ff71752

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Strings/Basic/IsomorphicString.txt

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
Given two strings s and t, determine if they are isomorphic.
2+
3+
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
4+
5+
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.
6+
7+
8+
Video: https://www.youtube.com/watch?v=6Qkail843d8
9+
10+
class Solution {
11+
public:
12+
bool isIsomorphic(string s, string t) {
13+
unordered_map<char, char> mp1;
14+
unordered_map<char, bool> mp2;
15+
16+
for (int i = 0; i < s.size(); i++) {
17+
18+
if(mp1[s[i]]){
19+
if(mp1[s[i]]!=t[i]){
20+
return false;
21+
}
22+
}
23+
else{
24+
if(mp2[t[i]]==true){
25+
return false;
26+
}
27+
else{
28+
mp1[s[i]]=t[i];
29+
mp2[t[i]]=true;
30+
}
31+
}
32+
33+
34+
}
35+
36+
return true;
37+
}
38+
39+
};
40+
41+
TC: O(n*(logm+logn)) SC: O(n)
42+
43+
44+
Here is the algorithm
45+
So basically you need to check one-one mapping in bidirectional way
46+
First declare a hashmap for string1 and string 2
47+
Now, check wheter string 1 is already mapped with string 2
48+
If it is mapped, now check whether the same first string character is trying to map with different one
49+
If it is trying to map with different one, return false
50+
51+
Now, if the first string character is not mapped, you need to ensure that the second string character is already in use before, if it used before, return false
52+
If the second string character is not used before, just map the first one with second one and mark second one to true.
53+
54+
55+
Intuition: First string character should not match twice with string 2
56+
Second string character should not match twice with string 1

0 commit comments

Comments
 (0)