【字符串】657. 机器人能否返回原点
题目:

解法:
我们可以模拟每个指令后机器人所在的位置。
算法:
一开始,机器人在 (x, y) = (0, 0)。如果指令是 'U',机器人会走到 (x, y-1),如果指令是 'R',机器人会走到 (x, y) = (x+1, y),以此类推。
1 class Solution { 2 public: 3 bool judgeCircle(string moves) 4 { 5 int x = 0; 6 int y = 0; 7 8 for (int i = 0; i < moves.size(); i++) 9 { 10 if (moves[i] == 'U') 11 { 12 y -= 1; 13 } 14 else if (moves[i] == 'D') 15 { 16 y += 1; 17 } 18 else if (moves[i] == 'L') 19 { 20 x -= 1; 21 } 22 else if (moves[i] == 'R') 23 { 24 x += 1; 25 } 26 } 27 28 return (x == y) && (y == 0); 29 30 } 31 };

浙公网安备 33010602011771号