题目大意:问一个机器人按照所指示的方向(一个字符串)走完之后会不会回到原点。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;
}
};