657.Judge Route Circle

来源:互联网 发布:云免ip怎么换成域名 编辑:程序博客网 时间:2024/05/20 21:45

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
看到这个题目,首先想到要遍历字符串,使其中的UD,RL个数分别相等;如此设置变量u,d,r,l分别记录字符出现次数。然后用for循环遍历字符串,在循环
中用4个if语句检查字符。代码如下:
bool judgeCircle(char* moves) {    int r,l,u,d,i;    i=r=l=u=d=0;    while(moves[i]!='\0')    {                if(moves[i]=='R')            r=r+1;       else if(moves[i]=='L')            l=l+1;       else if(moves[i]=='U')            u=u+1;       else if(moves[i]=='D')            d=d+1;        i++;    }    if(r==l&&u==d)        return true;    else     return false;}
后来我看其他人的题解,发现了更简洁的办法,代码如下:
bool judgeCircle(char* moves) {    int x=0,y=0;    for(int i=0;i<strlen(moves);i++)        switch(moves[i])        case'U':y--;break;        case'D':y++;break;        case'R':x--;break;        case'L':x++;break;    if(x==0&&y==0)        return true;    else        return false;} 此方法使用switch语句,很好的替代了if语句的臃肿,可见,在有选择的情况下,考虑switch可能会有意外的收获。   




 
原创粉丝点击