Leetcode 657. Robot Return to Origin

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Robot Return to Origin

2. Solution

  • Version 1
class Solution {
public:
    bool judgeCircle(string moves) {
        int vertical = 0;
        int horizontal = 0;
        for(char ch : moves) {
            if(ch == 'L') {
                horizontal--;
            }
            else if(ch == 'R') {
                horizontal++;
            }
            else if(ch == 'U') {
                vertical++;
            }
            else {
                vertical--;
            }
        }
        return vertical == 0 && horizontal == 0;
    }
};
  • Version 2
class Solution {
public:
    bool judgeCircle(string moves) {
        int vertical = 0;
        int horizontal = 0;
        for(char ch : moves) {
            switch(ch) {
                case 'L':
                    horizontal--;
                    break;
                case 'R':
                    horizontal++;
                    break;
                case 'U':
                    vertical++;
                    break;
                case 'D':
                    vertical--;
                    break;
            }
        }
        return vertical == 0 && horizontal == 0;
    }
};

Reference

  1. https://leetcode.com/problems/robot-return-to-origin/description/

你可能感兴趣的:(Leetcode 657. Robot Return to Origin)