問題(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
大意:
一開始睦优,有一個(gè)機(jī)器在(0,0)的位置孔祸。給出一個(gè)移動(dòng)序列,判斷機(jī)器是否運(yùn)動(dòng)了一個(gè)環(huán)逗爹,所謂環(huán)就是運(yùn)動(dòng)回了初始位置橘原。
移動(dòng)序列由字符串表示。每次移動(dòng)由一個(gè)字符表示。有效的機(jī)器移動(dòng)是R(右)申尤、L(左)、U(上)和D(下)衙耕。輸出應(yīng)該是true和false來表示機(jī)器是否運(yùn)動(dòng)了一個(gè)環(huán)昧穿。
例1:輸入:“UD”
輸出:true例2:
輸入:“LL”
輸出:false
思路:
題目已經(jīng)指出了做法的關(guān)鍵——坐標(biāo)。定義x橙喘、y兩個(gè)坐標(biāo)时鸵,初始為0,根據(jù)上下左右的移動(dòng)方式來修改x和y的值厅瞎,最后看x和y是不是還是0饰潜,如果是則是回到了原味了。
需要注意的是和簸,雖然沒嘗試彭雾,但看題目的意思應(yīng)該是有陷阱在于輸入的字符串不僅僅包含著四個(gè)字母,還可能有別的锁保,所以要對這四個(gè)字母專門判斷(else if)薯酝,不能隨便用個(gè)else南誊。還有就是C++創(chuàng)建int變量并不會默認(rèn)初始化為0,而是一個(gè)最大值蜜托,需要手動(dòng)初始化為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