-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsomorphic_Strings.cpp
More file actions
51 lines (51 loc) · 1.46 KB
/
Isomorphic_Strings.cpp
File metadata and controls
51 lines (51 loc) · 1.46 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
class Solution
{
public:
/*Isomorphic Strings 分别记录s到t,t到s的单词映射,32ms*/
bool isIsomorphic(string s, string t)
{
if (s.length() != t.length()) return false;
//记录s到t的映射
unordered_map<char, char> mp;
for (int i = 0; i < s.length(); ++i)
{
if (mp.find(s[i]) == mp.end())
mp[s[i]] = t[i];
else if (mp[s[i]] != t[i])
return false;
}
//记录t到s的映射
mp.clear();
for (int i = 0; i < s.length(); ++i)
{
if (mp.find(t[i]) == mp.end())
mp[t[i]] = s[i];
else if (mp[t[i]] != s[i])
return false;
}
return true;
}
/*Isomorphic Strings 分别记录s到t,t到s的单词映射,用数组,8ms*/
bool isIsomorphic_v2(string s, string t)
{
if (s.length() != t.length())
return false;
int map1[256], map2[256];
fill_n(map1, 256, 0);
fill_n(map2, 256, 0);
for (int i = 0; i < s.length(); i++)
{
//s到t的映射检查
if (map1[s[i]] == 0)
map1[s[i]] = t[i];
else if (map1[s[i]] != t[i])
return false;
//t到s的映射检查
if (map2[t[i]] == 0)
map2[t[i]] = s[i];
else if (map2[t[i]] != s[i])
return false;
}
return true;
}
};