Leetcode 657 Robot Return to Origin 机器回归原点
在2D平面上有一个从位置(0,0)开始的机器人。 给定其移动序列,判断该机器人在完成移动后是否在(0,0)处结束。
移动序列由字符串表示,字符move [i]表示其第i个移动。 有效移动是R(右),L(左),U(上)和D(下)。 如果机器人在完成所有移动后返回原点,则返回true。 否则,返回false。
注意:机器人“面对”的方式无关紧要。 “R”将始终使机器人向右移动一次,“L”将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
Example 1:
Input: "UD"
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.Example 2:
Input: "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.解题思路
先把上下左右都定义成数值,然后用for loop 把字母给列一遍
class Solution {
public boolean judgeCircle(String moves) {
int horizontal = 0;
int vertical = 0;
HashMap<Character, Integer> map = new HashMap<>();
map.put('U', 1);
map.put('D', -1);
map.put('L', 1);
map.put('R', -1);
for (Character c: moves.toCharArray()) {
if (c == 'U' || c == 'D') {
horizontal += map.get(c);
} else {
vertical += map.get(c);
}
}
return horizontal == 0 && vertical == 0;
}
}