Saturday, September 30, 2017

[LeetCode]Judge Route Circle


很简单的题目,对x和y分别记录,看最后是否有位移即可。当然题目也可以变为路径上时候存在环,我们用set记录每个时刻的位置即可。对这道题来说,常数空间,Linear time即可解,代码如下:


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