ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

1496. Path Crossing

2020-06-29 23:06:42  阅读:361  来源: 互联网

标签:set ver get pos else 1496 path Crossing Path


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

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

标签:set,ver,get,pos,else,1496,path,Crossing,Path
来源: https://www.cnblogs.com/wentiliangkaihua/p/13210926.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有