Advertisement
657. Robot Return to Origin
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Approach
Count horizontal (L/R) and vertical (U/D) moves separately; return true only if both net displacements are zero.
657.cs
C#
// Approach: Count horizontal (L/R) and vertical (U/D) moves separately;
// return true only if both net displacements are zero.
// Time: O(n) Space: O(1)
public class Solution
{
public bool JudgeCircle(string moves)
{
int right = 0;
int up = 0;
foreach (char move in moves)
{
switch (move)
{
case 'R':
right++;
break;
case 'L':
right--;
break;
case 'U':
up++;
break;
case 'D':
up--;
break;
}
}
return right == 0 && up == 0;
}
}Advertisement
Was this solution helpful?