题目
在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
思路
遍历一下字符串,统计一下对于向左向右或者向上向下的个数,只要向左向右 或者向上向下不相等,就返回false。否则为true。
代码
class Solution {
public boolean judgeCircle(String moves) {
int left=0;
int right=0;
int up=0;
int down=0;
char temp;
for (int i=0;i<moves.length();++i)
{
temp=moves.charAt(i);
if (temp=='U')
++up;
else
{
if (temp=='D')
++down;
else
{
if (temp=='L')
++left;
else
++right;
}
}
}
return left==right && up==down;
}
}
结果
太暴力了,这个跟那种设定一个坐标,然后移动没什么区别。
改进思路
不用统计每个的个数,把左边提取出来,只要是向上的就加1,向下就减1,向右就加1,向左就减1.看看最后两个数是不是都是为0。
代码
class Solution {
public boolean judgeCircle(String moves) {
int horizontal=0; //水平
int perpendicular=0; //垂直
char temp;
for (int i=0;i<moves.length();++i)
{
temp=moves.charAt(i);
if (temp=='L')
--horizontal;
else
if (temp=='R')
++horizontal;
else
if (temp=='U')
++perpendicular;
else
--perpendicular;
}
return horizontal==0 && perpendicular==0;
}
}
结果
还是没有什么大的进步。,消耗的内存也多。我思来想去,应该是这 if - else的语句过多造成的,想办法把这部分代码去了
再改进思路
利用一个数组,来UDLR的个数,最后返回他们个数相等即可。
代码
class Solution {
public boolean judgeCircle(String moves) {
int a[]=new int[26];
char temp;
for (int i=0;i<moves.length();++i)
{
temp=moves.charAt(i);
a[temp-'A']++;
}
return a[3]==a[20] && a[11]==a[17];
}
}
结果
经过这样把 if - else 语句消去,这样我们可以降低了运行速度。