心得:
控制機器人走路,且最後必須回到起點,把它當作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) andD(down). The output should be true or false representing whether the robot makes a circle.Example 1:
Input: "UD" Output: trueExample 2:
Input: "LL" Output: false
答案:
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:
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;
}
}