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;
        }
    }

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

  • 相关阅读:
    VS2010中经常使用的快捷键
    IE无法打开internet网站已终止操作的解决的方法
    Spring3.0 AOP 具体解释
    Java 反射机制[Method反射]
    软件測试自学指南---从入门到精通
    Java中Map的使用
    tracert路由跟踪命令分析判断
    C++ Primer 学习笔记_32_STL实践与分析(6) --再谈string类型(下)
    ORACLE触发器具体解释
    Androidclient推断server是否开启 HttpHostException解决方式
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13210926.html
Copyright © 2011-2022 走看看