657. Judge Route Circle 判断路线成圈


1.c++

首先是我最先想到的解法

class Solution {
public:
    bool judgeCircle(string moves) {
        int u_num=0,d_num=0,r_num=0,l_num=0;//定义上下左右走了多少步
        int sum=0;
        for(int i=0;i<moves.length();i++){
            if(moves[i]=='R'){r_num++;}
            if(moves[i]=='L'){l_num++;}
            if(moves[i]=='U'){u_num++;}
            if(moves[i]=='D'){d_num++;}
        }
        sum=r_num-l_num+u_num-d_num;
        if(sum==0)
            return true;
        else
            return false;
    }
};

最直接也最简单,只要上的步数减去下的步数加上左的步数减去右的步数为0就判断回到原点。

看别人的,也是一个意思

class Solution {
public:
    bool judgeCircle(string moves) {
        int len=moves.length();
        int x=0,y=0;
        for(int i=0;i<len;i++)
        {
            if(moves[i]=='U')y++;
            else if(moves[i]=='D')y--;
            else if(moves[i]=='R')x++;
            else x--;
        }
        if(x==0&&y==0)return true;
        else return false;
    }
};

我感觉和为0也行,&&也行,因为和不为0就说明不能抵消,反正作用一样,但是还是&&更严谨,c++也可以用switch

2.java

class Solution{
    public boolean judgeCircle(String moves) {
        int v = 0, h = 0;
        for (char move : moves.toCharArray()) {
            switch (move) {
                case 'U': v++; break;
                case 'D': v--; break;
                case 'R': h++; break;
                case 'L': h--; break;
            }
        }
        return v == 0 && h == 0;
    } 
}

3.python

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """ 
        return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
python实在太简洁了,生气



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值