Leetcode

Robot Return to Origin

  • Time:Time:
  • Space:Space:

C++

class Solution {
 public:
  bool judgeCircle(string moves) {
    int right = 0;
    int up = 0;

    for (const char move : moves) {
      switch (move) {
        case 'R':
          ++right;
          break;
        case 'L':
          --right;
          break;
        case 'U':
          ++up;
          break;
        case 'D':
          --up;
          break;
      }
    }

    return right == 0 && up == 0;
  }
};

JAVA

class Solution {
  public boolean judgeCircle(String moves) {
    int right = 0;
    int up = 0;

    for (final char move : moves.toCharArray()) {
      switch (move) {
        case 'R':
          ++right;
          break;
        case 'L':
          --right;
          break;
        case 'U':
          ++up;
          break;
        case 'D':
          --up;
          break;
      }
    }

    return right == 0 && up == 0;
  }
}

Python

class Solution:
  def judgeCircle(self, moves: str) -> bool:
    return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D')