leetcode-657-Judge Route Circle

题目描述:

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

 

要完成的函数:

bool judgeCircle(string moves) 

说明:

1、这道题目不难,看到给的两个例子之后,第一时间就想到了括号匹配,但这道题目比括号匹配还容易。

给定的string之中,U和D的个数必须相等,L和R的个数必须相等,最后才会回到原点。

所以我们可以设计两个变量count1和count2来存储这两种信息,如下构造代码:

    bool judgeCircle(string moves) 
    {
        int count1=0,count2=0;
        int s1=moves.size();
        for(int i=0;i<s1;i++)
        {
            if(moves[i]=='U')
                count1++;
            else if(moves[i]=='D')
                count1--;
            else if(moves[i]=='L')
                count2--;
            else if(moves[i]=='R')
                count2++;
        }
        if(count1==0&&count2==0)
            return true;
        else
            return false;
    }

上述代码遍历一遍给定的字符串,就可以得到结果,十分简洁。

上述代码实测19ms,beats 95.68% of cpp submissions。

2、改进:

上述这种做法在for循环内部不断地条件判断,这样做有点浪费时间。

笔者原本想改成unordered_map来存储,每次碰到一个字母,直接用unordered_map就得到要+1还是-1的结果。

但面临一个问题,怎样区分开UD和LR?碰到U是+1,碰到R也是+1。

同学们有什么想法吗?或者使用别的更加快的方法来完成这道题目?

欢迎在评论中留言!

猜你喜欢

转载自www.cnblogs.com/king-3/p/9023515.html
今日推荐