leetcode657——Judge Route Circle

题目大意:问一个机器人按照所指示的方向(一个字符串)走完之后会不会回到原点。UDLR分别代表上下左右。

分析:字符串应用

代码:

class Solution {
public:
int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
bool judgeCircle(string moves) {
int x = 0, y = 0;
for(int i = 0;i < moves.size();i++) {
int choice;
if (moves[i] == 'U')
choice = 0;
else if (moves[i] == 'D')
choice = 1;
else if (moves[i] == 'L')
choice = 2;
else choice = 3;
x = x + dir[choice][0];
y = y + dir[choice][1];
}
if (x == 0 && y == 0)
return true;
else return false;
}

};

后来想出了一种更简便的思路:

class Solution {
public:
bool judgeCircle(string moves) {
int x = 0, y = 0;
for (int i = 0;i < moves.size();i++) {
if (moves[i] == 'U') x--;
else if (moves[i] == 'D') x++;
else if (moves[i] == 'L') y--;
else y++;
}
if (x == 0 && y == 0) return true;
else return false;
}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值