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.
Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
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.
Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
Example 1:
Input: moves = "UD"
Output: true
Approach
Java
public class RobotReturnToOrigin {public static void main(String[] args) {String moves = "UD";System.out.println(judgeCircle(moves));}static boolean judgeCircle(String s) {int n = s.length();int L = 0, R = 0, U = 0, D = 0;for (int i = 0; i < n; i++) {if (s.charAt(i) == 'L')L++;else if (s.charAt(i) == 'R')R++;else if (s.charAt(i) == 'U')U++;else if (s.charAt(i) == 'D')D++;}int x = U - D, y = R - L;if (x == 0 && y == 0)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool judgeCircle(string s){int n = s.size();int L = 0, R = 0, U = 0, D = 0;for (int i = 0; i < n; i++){if (s[i] == 'L')L++;else if (s[i] == 'R')R++;else if (s[i] == 'U')U++;else if (s[i] == 'D')D++;}int x = U - D, y = R - L;if (x == 0 && y == 0)return true;return false;}int main(){string moves = "UD";if (judgeCircle(moves))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment