1. 程式人生 > >LeetCode 657.Robot Return to Origin( 機器人能否返回原點) C++ JAVA實現

LeetCode 657.Robot Return to Origin( 機器人能否返回原點) C++ JAVA實現

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

Input: "UD"
Output: true 
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

Input: "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

在二維平面上,有一個機器人從原點 (0, 0) 開始。給出它的移動順序,判斷這個機器人在完成移動後是否在 (0, 0) 處結束

移動順序由字串表示。字元 move[i] 表示其第 i 次移動。機器人的有效動作有 R

(右),L(左),U(上)和 D(下)。如果機器人在完成所有動作後返回原點,則返回 true。否則,返回 false。

注意:機器人“面朝”的方向無關緊要。 “R” 將始終使機器人向右移動一次,“L” 將始終向左移動等。此外,假設每次移動機器人的移動幅度相同。

示例 1:

輸入: "UD"
輸出: true
解釋:機器人向上移動一次,然後向下移動一次。所有動作都具有相同的幅度,因此它最終回到它開始的原點。因此,我們返回 true。

示例 2:

輸入: "LL"
輸出: false
解釋:機器人向左移動兩次。它最終位於原點的左側,距原點有兩次 “移動” 的距離。我們返回 false,因為它在移動結束時沒有返回原點。

思路一:對字串moves進行遍歷,統計U D L R字元出現的個數,如果U = D,L = R,則返回true,否則返回false

對此精簡,僅需設定兩個變數countL ,countD 當 D出現時countD++,當U出現時countD--。最後計算是否等於0即可。

C++程式碼實現:

class Solution {
public:
    bool judgeCircle(string moves) {
        int countL = 0,countU = 0;
        for(int i = 0; i < moves.length(); i++)
        {
            if(moves[i] == 'D')
                countU--;
            else if(moves[i] == 'U')
                countU++;
            else if(moves[i] == 'L')
                countL++;
            else
                countL--;
        }
        if(countL == 0 && countU == 0)
            return true;
        else
            return false;
    }
};
static const int _ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    return 0;
}();

JAVA程式碼實現:

繼續做了簡化,如果moves字串的長度不是偶數,則直接return false;

class Solution {
    public boolean judgeCircle(String moves) {
        if((moves.length() >> 1) << 1 != moves.length() )
            return false;
        char []ch = moves.toCharArray();
        int []arr = new int[126];
        for(char st : ch)
        {
            arr[st]++;
        }
        if(arr['U'] == arr['D'] && arr['L'] == arr['R'])
            return true;
        else
            return false;
    }
}