657. Judge Route Circle 判断路线成圈

xiaoxiao2021-02-28  2

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实在太简洁了,生气

转载请注明原文地址: https://www.6miu.com/read-1600306.html

最新回复(0)