657. Robot Return to Origin
2024-10-15 09:04:22
Description
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.
Example:
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.
分析:
- 设置x = 0, y = 0;
- 一次检查每一个字符,分别改变x,y的值
- 最后查看x、y是否都是0
class Solution {
public boolean judgeCircle(String moves) {
Robot r = new Robot();
char[] chars = moves.toCharArray();
for(char c: chars){
if(c == 'R') r.x++;
else if(c == 'L') r.x--;
else if(c == 'U') r.y++;
else r.y--;
}
if(r.x == 0 && r.y == 0) return true;
else return false;
}
class Robot{
int x;
int y;
public Robot(){
this.x = 0;
this.y = 0;
}
}
}
最新文章
- 代码中,使用__DATE__宏,获取程序编译时间,如何保证每次编译代码(非重新生成方式),都能更新__DATE__的值?
- OpenGL法向量变换
- HDU 1693 Eat the Trees(插头DP、棋盘哈密顿回路数)+ URAL 1519 Formula 1(插头DP、棋盘哈密顿单回路数)
- servlet&;jsp高级:第三部分
- 网站注册信息的JS全码
- Oracle CheckPoint进程
- java设计模式--结构型模式--装饰模式
- Hdu2425-Hiking Trip(优先队列搜索)
- Spark IDEA开发环境构建
- 「OC」 继承
- 结对编程之<;GoldPointGame>;
- 嵌入式-迅为iTOP-4418开发板Flash空间问题
- 一道有意思的找规律题目 --- CodeForces - 964A
- Oracle drop table 和 truncate table对grant授权的影响
- perl 读写文件
- Ubuntu创建新用户并设置权限
- ArrayDeque源代码分析
- AdvStringGrid 删除数据
- oracle查询一个用户下的所有表
- python基础——Linux系统下的文件目录结构