Description:
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: true
Example 2:
Input: “LL”
Output: false
解題思路分析
本題判斷移動後是否回到原點,解題思路很簡單:首先聲明兩個int型變量x,y作爲座標,遍歷字符串若爲R則x++,若爲L則x–,若爲U則y++,若爲D則y–;遍歷結束後比較x,y是否爲0 =,均爲0則返回true。
時間複雜度爲O(n),n爲字符串長度。
代碼
class Solution {
public:
bool judgeCircle(string moves) {
int x = 0, y = 0;
for (std::string::iterator it=moves.begin(); it!=moves.end(); ++it) {
if (*it == 'R') {
x++;
} else if (*it == 'L') {
x--;
} else if (*it == 'U') {
y++;
} else if (*it == 'D') {
y--;
}
}
if (x == 0 && y == 0) return true;
return false;
}
};