-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay45.cpp
More file actions
57 lines (45 loc) · 1.18 KB
/
Day45.cpp
File metadata and controls
57 lines (45 loc) · 1.18 KB
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
/*
This problem was asked by Bloomberg.
Determine whether there exists a one-to-one character mapping from one string s1 to another s2.
For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d.
Given s1 = foo and s2 = bar, return false since the o cannot map to two characters.
*/
#include <iostream>
#include <unordered_map>
#include <unordered_set>
using namespace std;
bool hasOneToOneMapping(const string &s1, const string &s2)
{
if (s1.length() != s2.length())
return false;
unordered_map<char, char> mapping;
unordered_set<char> mapped_chars;
for (int i = 0; i < s1.length(); i++)
{
char c1 = s1[i];
char c2 = s2[i];
if (mapping.count(c1))
{
if (mapping[c1] != c2)
return false;
}
else
{
if (mapped_chars.count(c2))
return false;
mapping[c1] = c2;
mapped_chars.insert(c2);
}
}
return true;
}
int main()
{
string s1 = "foo";
string s2 = "bar";
if (hasOneToOneMapping(s1, s2))
cout << "Exists";
else
cout << "Doesn't exist";
return 0;
}