657. Judge Route Circle-Difficulty:Easy

来源:互联网 发布:苹果aso优化 编辑:程序博客网 时间:2024/06/06 00:34

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

算法分析:只要往上走的距离等于往下走的距离,往左走的距离等于往右走的距离,即能够回到原点。

C语言版

bool judgeCircle(char* moves) {    int r = 0, l = 0, u = 0, d = 0, i;    for(i = 0; moves[i] != '\0'; i++)    {        switch(moves[i])        {            case 'R' : r++; break;            case 'L' : l++; break;            case 'U' : u++; break;            default : d++; break;        }    }    if(r == l && u == d)        return true;    else        return false;}

Python版

class Solution(object):    def judgeCircle(self, moves):        """        :type moves: str        :rtype: bool        """        #一行入魂        return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D')