1496. Path Crossing
package LeetCode_1496 /** * 1496. Path Crossing * https://leetcode.com/problems/path-crossing/ * Given a string path, where path[i] = 'N', 'S', 'E' or 'W', * each representing moving one unit north, south, east, or west, respectively. * You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return True if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False otherwise. Example 1: Input: path = "NES" Output: false Explanation: Notice that the path doesn't cross any point more than once. * */ class Solution { /* * solution: HashSet, checking position if had walk before, Time:O(n), Space:O(n) * */ fun isPathCrossing(path: String): Boolean { val set = HashSet<Pair<Int, Int>>() //add starting point set.add(Pair(0, 0)) var x = 0 var y = 0 for (c in path) { when (c) { 'N' -> y++//north 'S' -> y--//south 'E' -> x++//east 'W' -> x--//west } val location = Pair(x, y) if (set.contains(location)) { return true } set.add(location) } return false } }