-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode205_isomorphic_strings.cpp
73 lines (58 loc) · 1.6 KB
/
leetcode205_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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @file leetcode205_isomorphic_strings.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2023/06/03 14:09
* @brief https://leetcode.com/problems/isomorphic-strings
*
**/
#include <iostream>
#include <map>
#include <string>
#include <set>
using namespace std;
class Solution {
public:
bool isIsomorphic(string s, string t) {
std::map<char, char> m;
std::set<char> used;
if (s.empty() || t.empty()) {
return false;
}
size_t len = s.length();
for (size_t i = 0; i < len; ++i) {
char c = s[i];
auto it = m.find(c);
if (it == m.end()) {
// Try to map to a char that is already used
if (used.find(t[i]) != used.end()) {
return false;
}
m.insert({s[i], t[i]});
used.insert(t[i]);
} else {
if (it->second != t[i]) {
return false;
}
}
}
return true;
}
};
int main() {
while (1) {
std::cout << "string s (Ctrl-C to exit): ";
std::string s;
if (!std::getline(std::cin, s)) {
return 0;
}
std::cout << "string t (Ctrl-C) to exit: ";
std::string t;
if (!std::getline(std::cin, t)) {
return 0;
}
Solution solution;
auto ret = solution.isIsomorphic(s, t);
std::cout << (ret ? "true" : "false") << std::endl;
}
return 0;
}