[C#][LeetCode][Easy] 657. Judge Route Circle

心得:

控制機器人走路,且最後必須回到起點,把它當作XY軸來理解的話很快就可以解答。
右 X + 1, 左 X - 1, 上 Y + 1, 下 Y - 1,最後 X 與 Y 皆為0則回傳true

問題:

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:

1
2
3
4
5
6

**Input:** "UD"
>
> **Output:** true
>
>

Example 2:

1
2
3
4
5
6

**Input:** "LL"
>
> **Output:** false
>
>

答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
public bool JudgeCircle(string moves) {
int x = 0;
int y = 0;

foreach (var item in moves)
{
switch (item)
{
case 'U':
{
y++;
break;
}
case 'D':
{
y--;
break;
}
case 'R':
{
x++;
break;
}
case 'L':
{
x--;
break;
}
}
}

return (x == 0 && y == 0);
}
}

`

答案 - Linq:

1
2
3
4
5
6
7
8

public class Solution {
public bool JudgeCircle(string moves) {
int x = moves.Where(p => p == 'U' || p == 'D').Sum(p => (p == 'U') ? 1 : -1);
int y = moves.Where(p => p == 'R' || p == 'L').Sum(p => (p == 'R') ? 1 : -1);
return x == 0 && y == 0;
}
}