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

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

  • 相关阅读:
    【XAF】非持久化对象分组和属于不同会话
    【原创】XAF 非持久对象界面中更新xpo的状态查询
    Java字符串操作方法集
    Java易忘知识点统计
    Android常用依赖库搜集
    Android Studio报错Unable to resolve dependency for ':app@release/compileClasspath':无法引用任何外部依赖的解决办法
    Codewars练习Python
    Python学习日记之正则表达式re模块
    Linux学习日记之crontab使用notify-send实现每小时通知提醒
    Linux学习日记之Deepin下查看crontab运行日志
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13210926.html
Copyright © 2020-2023  润新知