Python版本:Python3.6.2
657. Judge Route Circle
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
先贴自己的代码:
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
l = r = u = d = 0
if len(moves) % 2 == 0: #字符个数为偶数,可能是循环,也可能不是循环
for i in range(len(moves)):
if moves[i] == "L":
l += 1
if moves[i] == "R":
r += 1
if moves[i] == "U":
u += 1
if moves[i] == "D":
d += 1
if l == r and u == d: ##痛点
return True
else:
return False
else:
return False
上面是定义的函数,下面检验一下到底对不对:
a = "UD"
x = Solution()
print(x.judgeCircle(moves=a))
输出 True 棒棒哒!
很久没有写过程序,竟然写这700+道题目里最简单的题目,都有困难,痛点在于 and ,之前一直编译不成功是因为我没用and,而是想当然的用的&哎,基本功全还给老师了/(ㄒoㄒ)/~~
and 和 &的区别:
- and:逻辑运算符:真 and 假 = 假 ;真 and 真 = 真
- &:位运算符:按位与,10 &11 = 10
下面贴大神的代码:2行搞定(T_T)
class Solution:
def judgeCircle(self, moves):
return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
大神如此之快是因为用了神器——函数count(),可以计算子字符串在字符串中出现的次数。