Skip to content

Commit 1aedbf9

Browse files
authored
Create solution.cpp
1 parent e2f6db1 commit 1aedbf9

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

IsomorphicStrings/solution.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include <unordered_map>
2+
3+
class Solution {
4+
public:
5+
bool isIsomorphic(string s, string t)
6+
{
7+
// This vector will contain the letter pattern which needs to be
8+
// common between both strings s and t for them to be isomorphic
9+
vector<int> letterPattern;
10+
11+
// Use hashmap to map letters in string s to unique letterIds
12+
// Iterate over letters in string s building the letter pattern
13+
unordered_map<char, int> hashmapS;
14+
int maxLetterId = 0;
15+
for (int i=0; i<s.length(); i++)
16+
{
17+
char letter = s.at(i);
18+
19+
// check if new letter
20+
if (hashmapS.count(letter) == 0)
21+
hashmapS[letter] = ++maxLetterId;
22+
23+
letterPattern.push_back(hashmapS[letter]);
24+
}
25+
26+
// Perform a similar loop as before but now iterating over string t
27+
// Use a seperate hashmap for string t to map letters to letterIds
28+
unordered_map<char, int> hashmapT;
29+
maxLetterId = 0;
30+
for (int i=0; i<t.length(); i++)
31+
{
32+
char letter = t.at(i);
33+
34+
// check if new letter
35+
if (hashmapT.count(letter) == 0)
36+
hashmapT[letter] = ++maxLetterId;
37+
38+
// Here we compare the letterId we got for the current position in string t and string s before
39+
if (hashmapT[letter] != letterPattern.at(i))
40+
{
41+
// The letterIds are not the same so the letter pattern is different
42+
// Strings s and t are not isomorphic
43+
return false;
44+
}
45+
}
46+
47+
// If we reached here then the letter pattern generated for both string match meansing they are isomorphic
48+
return true;
49+
}
50+
};

0 commit comments

Comments
 (0)