zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    排序算法(I)冒泡排序
    C#常用类string
    HashMap----工作原理
    Java计算字符串中字母出现的次数
    数据库优化
    线程和进程的区别(详细)
    SpringMVC工作原理
    jsp运行原理及运行过程
    一个公告
    SR
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14165014.html
Copyright © 2011-2022 走看看