본문 바로가기
IT/알고리즘

25★] Leetcode 1496. Path Crossing

by 깻잎쌈 2020. 7. 5.
반응형

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

방향을 가리키는 문자열을 따라 이동했을 때 같은 점은 두 번 지나가는지 묻는 문제.

 

Path Crossing - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

for문으로 원점을 처음부터 하나씩 바꿔가면서

다시 원점으로 돌아가는지 확인한다.

class Solution {
public:
    bool isPathCrossing(string path) {
        bool ans = false;
        int upDown = 0;
        int leftRight = 0;
        
        for(int i = 0; i<path.size();i++){
            upDown = leftRight = 0;
            for(int j = i;j<path.size();j++){
          
              if(path[j]=='N')
                upDown++;
              else if(path[j]=='S')
                upDown--;
              else if(path[j]=='E')
                leftRight++;
              else if(path[j]=='W')
                leftRight--;
            
              if(leftRight ==0 &&  upDown ==0){
                 ans = true;
                 return ans;
            }
        }          
            
        }
                       
        return ans;
    }
};
반응형

댓글