很简单的题目,对x和y分别记录,看最后是否有位移即可。当然题目也可以变为路径上时候存在环,我们用set记录每个时刻的位置即可。对这道题来说,常数空间,Linear time即可解,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool judgeCircle(string moves) { | |
int x = 0, y = 0; | |
for(char& c : moves) | |
{ | |
switch(c) | |
{ | |
case 'U': | |
++y; | |
break; | |
case 'D': | |
--y; | |
break; | |
case 'L': | |
--x; | |
break; | |
case 'R': | |
++x; | |
break; | |
} | |
} | |
return !x && !y; | |
} | |
}; |
No comments:
Post a Comment