forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
path-crossing.cpp
41 lines (39 loc) · 1.04 KB
/
path-crossing.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
// Time: O(n)
// Space: O(n)
class Solution {
public:
bool isPathCrossing(string path) {
unordered_set<pair<int, int>, PairHash<int>> lookup = {{0, 0}};
int x = 0, y = 0;
for (const auto& c : path) {
switch(c) {
case 'E':
++x;
break;
case 'W':
--x;
break;
case 'N':
++y;
break;
case 'S':
--y;
break;
}
if (!lookup.emplace(x, y).second) {
return true;
}
}
return false;
}
private:
template <typename T>
struct PairHash {
size_t operator()(const pair<T, T>& p) const {
size_t seed = 0;
seed ^= std::hash<T>{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2);
seed ^= std::hash<T>{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
return seed;
}
};
};