leetcode657. Judge Route Circle

来源:互联网 发布:海信电视看电影软件 编辑:程序博客网 时间:2024/06/06 03:52

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

思路:比较简单,主要是一次遍历字符串,遇到RLUD就记录下来,因为最后要返回原点,所以上下之和或左右之和都必须为0,累加到最后判断即可.

class Solution {public:    bool judgeCircle(string moves) {        int count = 0;        for(int i = 0; i < moves.size(); i++) {            switch(moves[i]){                case 'R' : count += 1; break;                case 'L' : count += -1; break;                case 'U' : count += 2; break;                case 'D' : count += -2; break;            }        }        if(count == 0) return true;        else return false;    }};
原创粉丝点击