1496. Path Crossing

양성준·2025년 4월 20일

코딩테스트

목록 보기
28/102

문제

https://leetcode.com/problems/path-crossing/description/

풀이

class Solution {
    public boolean isPathCrossing(String path) {
        Set<String> set = new HashSet<>();
        int x = 0;
        int y = 0;
        set.add("0,0");

        for(char c : path.toCharArray()) {
            if(c == 'N') {
                y++;
            }
            if(c == 'S') {
                y--;
            }
            if(c == 'E') {
                x++;
            }
            if(c == 'W') {
                x--;
            }

            String current = x+","+y;
            if(set.contains(current)) {
                return true;
            }
            set.add(current);
        }
        return false;
    }
}
  • 해당 좌표를 방문했는지 안했는지를 비교하기 위해 set을 사용
    • .contains가 O(1)의 시간복잡도를 가짐
  • set의 원소를 간편화하기 위해, x좌표와 y좌표를 더한 String값을 만들어 넣어줌
profile
백엔드 개발자

0개의 댓글