LeetCode 657. Judge Route Circle

来源:互联网 发布:sql数据库怎么建立 编辑:程序博客网 时间:2024/05/18 01:29

题目:
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

思路: 用一个pair变量(x,y)来保存坐标,遍历字符串中的每一个字符,如果为R,x加1;如果为L,x减1;如果为U,y加1;如果为D,y减1。如果最终坐标为(0,0),那么就代表在回到了原点,返回true。

代码:

class Solution {public:    bool judgeCircle(string moves) {        int len = moves.length();        pair<int, int> res(0, 0);//用pair保存坐标位置        for (int i = 0; i < len; ++i){            switch (moves[i]){//遍历字符串,按直接坐标分别对每一个字符进行判断            case 'R':                res.first += 1; break;            case 'L':                res.first -= 1; break;            case 'U':                res.second += 1; break;            case 'D':                res.second -= 1; break;            default:break;            }        }        return !(res.first+res.second);//如果最终坐标为(0,0)就为true    }};

结果: 19ms

原创粉丝点击