176.Judge Route Circle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010339647/article/details/79560748

题目

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

题目链接

https://leetcode.com/problems/judge-route-circle/description/

解题思路

问题转化:
条件1:给定的字符串中U和D的个数相等;
条件2:给定的字符串中R和L的个数相等;
只有两个条件同时满足,才可以说明可以回到出发的原点;

代码

java

public boolean judgeCircle(String moves) {
    int ud = 0;//记录出现U和D相抵之后的结果,遇到U加1,遇到D则减1;
    int rl = 0;
    int len = moves.length();
    for (int i = 0; i < len; i++) {
        char c = moves.charAt(i);
        switch(c){
        case 'U':
            ud++;
            break;
        case 'D':
            ud--;
            break;
        case 'R':
            rl++;
            break;
        case 'L':
            rl--;
            break;
        default:
            break;
        }
    }
    return ud == 0 && rl == 0;
    }

C++

bool judgeCircle(string moves) {
        int ud = 0;//记录出现U和D相抵之后的结果,遇到U加1,遇到D则减1;
        int rl = 0;
        int len = moves.size();
        for (int i = 0; i < len; i++) {
            char c = moves[i];
            switch(c){
                case 'U':
                    ud++;
                    break;
                case 'D':
                    ud--;
                    break;
                case 'R':
                    rl++;
                    break;
                case 'L':
                    rl--;
                    break;
                default:
                    break;
            }
         }
        return ud == 0 && rl == 0;

    }

python

def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        ud = 0;#记录出现U和D相抵之后的结果,遇到U加1,遇到D则减1;
        rl = 0;

        for c in moves :
            if c == 'U' :
                ud = ud + 1
            elif c == 'D':
                ud = ud - 1
            elif c == 'R':
                rl = rl + 1
            elif c == 'L':
                rl = rl - 1;

        return ud == 0 and rl == 0

总结

三种语言在实现本题目过程中语法上的区别

  • 逻辑运算符
    • java和C++ 中的与或非写法分别是 A&&B、A||B、!A,python中则是A and B, A or B, not A;
  • switch
    • java和C++有switch/case语法,python中没有;

猜你喜欢

转载自blog.csdn.net/u010339647/article/details/79560748
今日推荐