657. 机器人能否返回原点
题目描述
一个机器人站在平面坐标系的原点 (0, 0)。输入字符串 moves,按顺序描述它的每一步:'U' 向上、'D' 向下、'L' 向左、'R' 向右,每一步都只走一个单位。
方向与机器人的朝向无关,只按字符所指的绝对方向移动。
执行完全部指令后,如果机器人恰好回到原点,返回 true,否则返回 false。
示例 1
输入:moves = "UD" 输出:true
解释:上一步再下一步,回到原点。
示例 2
输入:moves = "LL" 输出:false
解释:连续向左两步,停在原点左边 2 个单位处。
数据范围
1 <= moves.length <= 2 * 10^4moves只包含'U'、'D'、'L'、'R'。
解题思路
用 x、y 记录机器人的坐标。逐个读指令:U 让 y 加 1,D 让 y 减 1,L 让 x 减 1,R 让 x 加 1。全部走完后检查 x 和 y 是否都为 0。
为什么正确
处理完前 i 条指令后,(x, y) 恰好是机器人当前的位置;x 等于已读的 R 数减 L 数,y 等于 U 数减 D 数。
复杂度分析
时间 O(n),额外空间 O(1)。
易错点
只看 x 或只看 y 不够,两个坐标都必须为 0。另外 U/D 只改 y、L/R 只改 x,不要把方向写反。
参考代码
Python、Java、C++、Go、JavaScript、TypeScript 六种语言,逻辑一致。
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for c in moves:
if c == 'U':
y += 1
elif c == 'D':
y -= 1
elif c == 'L':
x -= 1
else:
x += 1
return x == 0 and y == 0class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for (char c : moves.toCharArray()) {
if (c == 'U') {
y += 1;
} else if (c == 'D') {
y -= 1;
} else if (c == 'L') {
x -= 1;
} else {
x += 1;
}
}
return x == 0 && y == 0;
}
}class Solution {
public:
bool judgeCircle(string moves) {
int x = 0, y = 0;
for (char c : moves) {
if (c == 'U') {
y += 1;
} else if (c == 'D') {
y -= 1;
} else if (c == 'L') {
x -= 1;
} else {
x += 1;
}
}
return x == 0 && y == 0;
}
};func judgeCircle(moves string) bool {
x, y := 0, 0
for _, c := range moves {
if c == 'U' {
y += 1
} else if c == 'D' {
y -= 1
} else if c == 'L' {
x -= 1
} else {
x += 1
}
}
return x == 0 && y == 0
}var judgeCircle = function(moves) {
let x = 0, y = 0;
for (const c of moves) {
if (c === 'U') {
y += 1;
} else if (c === 'D') {
y -= 1;
} else if (c === 'L') {
x -= 1;
} else {
x += 1;
}
}
return x === 0 && y === 0;
};function judgeCircle(moves: string): boolean {
let x = 0, y = 0;
for (const c of moves) {
if (c === 'U') {
y += 1;
} else if (c === 'D') {
y -= 1;
} else if (c === 'L') {
x -= 1;
} else {
x += 1;
}
}
return x === 0 && y === 0;
}