C000_机器人能否返回原点(模拟题意)

一、题目描述

There is a robot starting at position (0, 0), the origin, on a 2D plane.
Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string,
and the character moves[i] represents its ith move.Valid moves are R (right), L (left), U (up), and D (down).
If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

二、题解

(1) 状态记录

/**
   * @thought:状态记录法
   * @date: 1/25/2020 9:21 PM
   * @Execution info:6ms 击败 87。78% 的j,38MB 击败 14.98% 的j
   * @Asymptotic Time Complexity:O()
   */
  public boolean judgeCircle(String moves) {
    int upAndDown = 0;
    int leftAndRight = 0;
    for(char c : moves.toCharArray()) {
      if(c == 'U')  upAndDown++;
      if(c == 'D')  upAndDown--;
      if(c == 'L')  leftAndRight++;
      if(c == 'R')  leftAndRight--;
    }
    return upAndDown == 0 && leftAndRight == 0;
  }

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( 1 ) O(1)
发布了309 篇原创文章 · 获赞 49 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104085159