題目地址:https://leetcode.com/problems/judge-route-circle/description/
大意:The valid robot moves are R (Right), L (Left), U (Up) and D (down). 給一個(gè)字符串,讓這個(gè)機(jī)器人按照字符串的字母走,看看能不能回到原點(diǎn)
其實(shí)很簡(jiǎn)單,看看R的個(gè)數(shù)和L的個(gè)數(shù)還有U的個(gè)數(shù)和D的個(gè)數(shù)這兩個(gè)都要相同就能回來了。
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
sp = list(moves)
if (sp.count('R') == sp.count('L') and sp.count('U') == sp.count('D')):
return True
else:
return False
a = Solution()
print (a.judgeCircle('LL'))
改進(jìn):
def judgeCircle2(self, moves):
"""
:type moves: str
:rtype: bool
"""
return moves.count('L') == moves.count('R') and moves.count('U') and moves.count('D')
知識(shí)點(diǎn):
string字符串是可以直接用count()方法的。返回值也不用判斷True和False是可以直接返回判斷表達(dá)式就可以了。