-
Notifications
You must be signed in to change notification settings - Fork 160
/
Mapstring.cpp
75 lines (48 loc) · 1.56 KB
/
Mapstring.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Two words are called isomorphic if the letters in one word can be mapped to get the second word.
Mapping a letter means replacing all occurrences of it with another letter while the ordering of the letters remains unchanged.
No two letters may map to the same letter, but a letter may map to itself.
Given two words as strings, check if they are isomorphic.
For example,
given "foo", "app"; returns true we can map f -> a and o->p
given "bar", "foo"; returns false we can't map both 'a' and 'r' to 'o'
given "ab", "ca"; returns true we can map 'a' -> 'b' and 'c' -> 'a'
*/
/*
solution; use two maps to record the map relation.
O(n) time, O(n) space
*/
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
bool CheckIsomorphicString(string str1, string str2) {
if(str1.size() != str2.size()) return false;
unordered_map<char, char>mp12;
unordered_map<char, char>mp21;
for (size_t i = 0; i < str1.size(); ++i) {
char char1 = str1[i];
char char2 = str2[i];
if (mp12.find(char1) != mp12.end()) {
if (mp12[char1] != char2) return false;
}
if (mp21.find(char2) != mp21.end()) {
if (mp21[char2] != char1) return false;
}
mp12[char1] = char2;
mp21[char2] = char1;
}
return true;
}
int main() {
string str1 = "foo";
string str2 = "app";
string str3 = "bar";
string str4 = "foo";
string str5 = "ab";
string str6 = "ca";
cout<<CheckIsomorphicString(str1, str2)<<endl;
cout<<CheckIsomorphicString(str3, str4)<<endl;
cout<<CheckIsomorphicString(str5, str6)<<endl;
return 0;
}