Leetcode Note: Go - Path Crossing
Path Crossing - LeetCode
https://leetcode.com/problems/path-crossing/
- Go 言語で取り組んだメモ
回答
[golang] O(n) using simple map and tuple struct - Path Crossing - LeetCode
https://leetcode.com/problems/path-crossing/solutions/710887/golang-o-n-using-simple-map-and-tuple-struct/
func isPathCrossing(path string) bool {
type Tuple struct{
X int
Y int
}
// map to record visited set of locations
visited := make(map[Tuple]int)
//starting positions
x:=0
y:=0
// add initial position to visited set
visited[Tuple{X: x, Y: y}]=0
for _, ch :=range path{
if string(ch)=="N"{
y++
} else if string(ch)=="S"{
y--
} else if string(ch)=="W"{
x--
} else if string(ch)=="E"{
x++
}
// found returns true if current position exists in set
_, found:= visited[Tuple{X: x, Y: y}]
if found{
return true
}
// add current position to visited set
visited[Tuple{X: x, Y: y}]=0
}
// no overlap after iterating through path
return false
}