美文网首页Leetcode
Leetcode 657. Robot Return to Or

Leetcode 657. Robot Return to Or

作者: SnailTyan | 来源:发表于2018-10-09 17:19 被阅读9次

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

    本文链接:https://www.haomeiwen.com/subject/qptyaftx.html