forked from kirito-udit/DSA-450
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsomorphic-Strings.cpp
51 lines (42 loc) · 1.43 KB
/
Isomorphic-Strings.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution{
public:
// This function returns true if str1 and str2 are ismorphic
// else returns false
bool areIsomorphic(string str1, string str2)
{
int m = str1.length(), n = str2.length();
// Length of both strings must be same for one to one
// corresponance
if (m != n)
return false;
// To mark visited characters in str2
bool marked[MAX_CHARS] = {false};
// To store mapping of every character from str1 to
// that of str2. Initialize all entries of map as -1.
int map[MAX_CHARS];
memset(map, -1, sizeof(map));
// Process all characters one by on
for (int i = 0; i < n; i++)
{
// If current character of str1 is seen first
// time in it.
if (map[str1[i]] == -1)
{
// If current character of str2 is already
// seen, one to one mapping not possible
if (marked[str2[i]] == true)
return false;
// Mark current character of str2 as visited
marked[str2[i]] = true;
// Store mapping of current characters
map[str1[i]] = str2[i];
}
// If this is not first appearance of current
// character in str1, then check if previous
// appearance mapped to same character of str2
else if (map[str1[i]] != str2[i])
return false;
}
return true;
}
};