Leetcode 657. Robot Return to Origin

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82985483

文章作者: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/

猜你喜欢

转载自blog.csdn.net/Quincuntial/article/details/82985483