問題(Easy):
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:Input: "UD"
Output: trueExample 2:
Input: "LL"
Output: false
大意:
一開始,有一個機器在(0,0)的位置。給出一個移動序列,判斷機器是否運動了一個環,所謂環就是運動回了初始位置。
移動序列由字符串表示。每次移動由一個字符表示。有效的機器移動是R(右)、L(左)、U(上)和D(下)。輸出應該是true和false來表示機器是否運動了一個環。
例1:輸入:“UD”
輸出:true例2:
輸入:“LL”
輸出:false
思路:
題目已經指出了做法的關鍵——坐標。定義x、y兩個坐標,初始為0,根據上下左右的移動方式來修改x和y的值,最后看x和y是不是還是0,如果是則是回到了原味了。
需要注意的是,雖然沒嘗試,但看題目的意思應該是有陷阱在于輸入的字符串不僅僅包含著四個字母,還可能有別的,所以要對這四個字母專門判斷(else if),不能隨便用個else。還有就是C++創建int變量并不會默認初始化為0,而是一個最大值,需要手動初始化為0。
代碼(C++):
class Solution {
public:
bool judgeCircle(string moves) {
int x = 0,y = 0;
for (int i = 0; i < moves.size(); i++) {
if (moves[i] == 'U') y++;
else if (moves[i] == 'D') y--;
else if (moves[i] == 'L') x--;
else if (moves[i] == 'R') x++;
}
// std::cout << "x:" << x << " y:" << y << std::endl;
if (x == 0 && y == 0) return true;
else return false;
}
};
合集:https://github.com/Cloudox/LeetCode-Record