1.问题描诉
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
Example 1:
Input: “UD”
Output: true
Example 2:
Input: “LL”
Output: false
来自 https://leetcode.com/problems/judge-route-circle/description/
2.题目分析:
给机器人一个字符串指令,机器人根据指令进行相应的运动,U代表向前,D代表向后,L代表向左,R代表向右,判断机器人最终是否回到原来的坐标。设坐标(UD,LR),根据方向进行坐标的加减,最后判断。
3.C++代码
//beats 17%
bool judgeCircle(string moves)
{
int UD = 0;
int LR = 0;
for (int i = 0; i<moves.length(); i++)
{
switch (moves[i])
{
case 'U':
UD++;
break;
case 'D':
UD--;
break;
case 'L':
LR++;
break;
case 'R':
LR--;
break;
default:
break;
}
}
if (UD == 0 && LR == 0)
return true;
else
return false;
}
//我的代码:(beats 77%)
bool judgeCircle2(string moves)
{
int UD = 0;
int LR = 0;
for (int i = 0; i < moves.length(); i++)
{
char c = moves[i];
if (c == 'U')
UD++;
else if (c == 'D')
UD--;
if (c == 'L')
LR++;
else if (c == 'R')
LR--;
}
if (UD == 0 && LR == 0)
return true;
else
return false;
}
4.switch case和if else的效率比较
上面的两种方法思路是一样的,但是运行的时间效率却相差很大。
switch与if..else 的执行的效率问题
下面来详细描述switch与ifelse的区别。
switch…case与if…else的根本区别在于,switch…case会生成一个跳转表来指示实际的case分支的地址,而这个跳转表的索引号与switch变量的值是相等的。从而,switch…case不用像if…else那样遍历条件分支直到命中条件,而只需访问对应索引号的表项从而到达定位分支的目的。
具体地说,switch…case会生成一份大小(表项数)为最大case常量+1的跳表,程序首先判断switch变量是否大于最大case 常量,若大于,则跳到default分支处理;否则取得索引号为switch变量大小的跳表项的地址(即跳表的起始地址+表项大小*索引号),程序接着跳到此地址执行,到此完成了分支的跳转。
来自 https://blog.youkuaiyun.com/kehui123/article/details/5298337
因此,当分支数较少时,用if else效率会更高。