zoukankan      html  css  js  c++  java
  • 1496. 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.
    

    Example 2:

    Input: path = "NESWW"
    Output: true
    Explanation: Notice that the path visits the origin twice.

    Constraints:

    • 1 <= path.length <= 10^4
    • path will only consist of characters in {'N', 'S', 'E', 'W}
    class Solution {
        public boolean isPathCrossing(String path) {
            List<Integer> pos = Arrays.asList(0,0);
            Set<List<Integer>> set = new HashSet();
            set.add(pos);
            // boolean cross = false;
            // System.out.println(pos.get(0) + " " + pos.get(1));
            for(char c: path.toCharArray()){
                int hor = pos.get(1);
                int ver = pos.get(0);
                if(c == 'N'){
                    ver++;
                }
                else if(c == 'S'){
                    ver--;
                }
                else if(c == 'E'){
                    hor++;
                }
                else hor--;
                // pos = ;
                //System.out.println(pos[0] + " " + pos[1]);
                pos = Arrays.asList(ver, hor);
            // System.out.println(pos.get(0) + " " + pos.get(1));
                if(set.contains(pos)) return true;
                else set.add(pos);
            }
            return false;
        }
    }

    simulation,起始是0,0,把途径的点表示成arraylist加入set中看有没有重复

    注意不能用array,因为就算两个数组元素相等,只要不是同1 reference也会判定不相等,而List的比较是也比较element。

    class Solution {
        public boolean isPathCrossing(String path) {
            int x = 0, y = 0;
            Set<String> set = new HashSet();
            set.add(x + "$" + y);
            for (char c : path.toCharArray()) {
                if (c == 'N') y++;
                else if (c == 'S') y--;
                else if (c == 'E') x++;
                else x--;
                String key = x + "$" + y;
                if (set.contains(key))
                    return true;
                set.add(key);
            }
            return false;
        }
    }

    像这种表示就更简单了,忘球了可惜,以前在哪里见过来着

  • 相关阅读:
    zookeeper集群的部署
    【转】始于Jupyter Notebooks:一份全面的初学者实用指南
    【转】Jupyter Notebook主题字体设置及自动代码补全
    【转】pip install 快速下载
    【转】Sublime Text 3 常用快捷键
    【转】Python——DataFrame基础操作
    【转】sqlite3 小结
    【转】SQLite3的安装与使用
    Python Pandas pandas.DataFrame.to_sql函数方法的使用
    处理异常 ‘try’——‘except’ 方法
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13210926.html
Copyright © 2011-2022 走看看