leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 32 】2021-10-11 - 657. 机器人能否返回原点 #49

Open azl397985856 opened 2 years ago

azl397985856 commented 2 years ago

657. 机器人能否返回原点

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/robot-return-to-origin/

前置知识

移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。

注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。

 

示例 1:

输入: "UD" 输出: true 解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。

示例 2:

输入: "LL" 输出: false 解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 false,因为它在移动结束时没有返回原点。

liuyangqiQAQ commented 2 years ago

暴力求解 最简单的就是if else

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0;
        int y = 0;
        for (int i = 0; i < moves.length(); i++) {
            char c = moves.charAt(i);
            if(c == 'L') {
                x--;
            }else if(c == 'R') {
                x++;
            }else if(c == 'U') {
                y++;
            }else if(c == 'D') {
                y--;
            }else {
                continue;
            }
        }
        return x == 0 && y == 0;
    }
}

时间复杂度: O(n) n为字符串长度

空间复杂度: O(1)

优化求解.利用累加。L和R一样,D和U一样

class Solution {
    public boolean judgeCircle(String moves) {
        char[] chars = new char[26];
        for (int i = 0; i < moves.length(); i++) {
            chars[moves.charAt(i) - 'A']++;
        }
        return chars['L' - 'A'] == chars['R' - 'A'] && chars['U' - 'A'] == chars['D' - 'A'];
    }
}

时间复杂度:O(N) N为字符串长度

空间复杂度:O(1) 26为常数系数

Jding0 commented 2 years ago

思路

转换成坐标上下左右,然后比较落点坐标与initial point

'''
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = 0
        y = 0
        for step in moves:
            if step == "U" or step == "u":
                y += 1
            elif step == "R" or step == "r":
                x += 1
            elif step == "D" or step == "d":
                y -= 1
            elif step == "L" or step == "l":
                x -= 1
        if x == 0 and y == 0:
            return True
        else:
            return False
'''
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        if moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D'):
            return True
        return False

复杂度

空间 $O(1)$ 时间 $O(N)$

leolisgit commented 2 years ago

思路

就根据move的类型,对x,y进行加减。最后判断是否是在原点。

代码

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0;
        int y = 0;

        for (char move : moves.toCharArray()) {
            switch (move) {
                case 'U':
                    y--;
                    break;
                case 'D':
                    y++;
                    break;
                case 'L':
                    x--;
                    break;
                case 'R':
                    x++;
                    break;
                default:
                    break;
            }
        }
        return x == 0 && y == 0;
    }
}

复杂度

时间:O(n)
空间:O(1)

taojin1992 commented 2 years ago
set x axis pointer, y axis pointer

Time: O(moves.length())
Space: O(1)

Code:

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        for (int i = 0; i < moves.length(); i++) {
            if (moves.charAt(i) == 'U') {
                y++;
            } else if (moves.charAt(i) == 'D') {
                y--;
            } else if (moves.charAt(i) == 'L') {
                x--;
            } else if (moves.charAt(i) == 'R') {
                x++;
            }
        }
        return x == 0 && y == 0;
    }
}
hengistchan commented 2 years ago

代码

class Solution {
public:
    bool judgeCircle(string moves) {
        int s[2] = {0};  // 一次为上下方向和左右方向
        for(char m: moves) {
            switch( m ) {
            case 'U': ++s[0]; break;
            case 'D': --s[0]; break;
            case 'L': ++s[1]; break;
            case 'R': --s[1]; break;
            }
        }
        return s[0]==0 && s[1]==0;

    }
};
laurallalala commented 2 years ago

代码

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        left, up = 0, 0
        for move in moves:
            if move == "L":
                left += 1
            elif move == "R":
                left -= 1
            elif move == "U":
                up += 1
            else:
                up -= 1
        return left == 0 and up == 0

复杂度

Yufanzh commented 2 years ago

Intuition

Simply loop through all the characters and assign changes to coordinates accordingly

Algorithm in python3

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = 0
        y = 0
        for i in range(len(moves)):
            if moves[i] == "L":
                x -= 1
            elif moves[i] == "R":
                x += 1
            elif moves[i] == "U":
                y += 1
            elif moves[i] == "D":
                y -= 1
        if x== 0 and y == 0:
            return True
        else:
            return False

Complexity Analysis:

qixuan-code commented 2 years ago

LC 657. Robot Return to Origin

Ideas

comment 74 ms, faster than 34.88%

python代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = y = 0
        for i in moves:
            if i == 'R':
                x += 1
            elif i == 'L':
                x -= 1
            elif i == 'U':
                y += 1
            else:
                y -= 1

        return True if y == 0 and x == 0 else False

复杂度分析

biscuit279 commented 2 years ago

思路:直接模拟

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        location = [0,0]
        for move in moves:
            if move == 'R':
                location[0] -= 1
            if move == 'L':
                location[0] += 1
            if move == 'U':
                location[1] += 1
            if move == "D":
                location[1] -= 1
        if location == [0,0]:
            return True
        else:
            return False

时间复杂度:O(N) 空间复杂度:O(1)

muimi commented 2 years ago

思路

模拟坐标移动

代码

class Solution {
  public boolean judgeCircle(String moves) {
    int x = 0, y = 0;
    for (char c : moves.toCharArray()) {
      if (c == 'L') x++;
      else if (c == 'R') x--;
      else if (c == 'U') y++;
      else if (c == 'D') y--;
    }
    return x == 0 && y == 0;
  }
}

复杂度

Victoria011 commented 2 years ago

思路

只考虑 'U' 和 'D' 能否抵消, 'L' 和 'R' 能否抵消, 所以对于 'U', 'D' 只关心 y 坐标, 'L' , 'R' 只关心 x 坐标。

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        currx, curry = 0, 0
        for i in range(len(moves)):
            if moves[i] == 'U':
                curry += 1
            elif moves[i] == 'L':
                currx -= 1
            elif moves[i] == 'D':
                curry -= 1
            else:
                currx += 1
        if currx == 0 and curry == 0:
            return True
        return False

复杂度分析

Runtime Complexity: O(N)

Space Complexity: O(1)

biancaone commented 2 years ago
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        location = [0,0]
        for move in moves:
            if move == 'R':
                location[0] -= 1
            if move == 'L':
                location[0] += 1
            if move == 'U':
                location[1] += 1
            if move == "D":
                location[1] -= 1
        if location == [0,0]:
            return True
        else:
            return False
L-SUI commented 2 years ago

/**

xiezhengyun commented 2 years ago

思路

/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function (moves) {
  var map = {
    R: 0,
    L: 0,
    U: 0,
    D: 0
  }
  for(let i in moves){
    map[moves[i]]++
  }
  return map.R === map.L && map.U === map.D
};

复杂度

chun1hao commented 2 years ago
var judgeCircle = function (moves) {
  let x = 0;
  let y = 0;
  for (let i of moves) {
    if (i == "L") {
      y++;
    } else if (i == "R") {
      y--;
    } else if (i == "U") {
      x++;
    } else {
      x--;
    }
  }
  return !x && !y;
};
ai2095 commented 2 years ago

LC657. Robot Return to Origin

https://leetcode.com/problems/robot-return-to-origin/

Topics

Similar Questions

Hard

Medium

思路

count the # of 'U', 'D', 'L', and 'R'. Compare the # to determine the result

代码 Python

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        counter = collections.Counter(moves)
        return counter['L'] == counter['R'] and counter['U'] == counter['D']

复杂度分析

时间复杂度: O(n)
空间复杂度:O(1)

15691894985 commented 2 years ago

【Day 32】657. 机器人能否返回原点

思路:按题意逻辑写就行,维护坐标

    class Solution:
        def judgeCircle(self, moves: str) -> bool:
            x = y = 0
            for move in moves:
                if move =='R':
                    x +=1
                if move == 'L':
                    x -= 1
                if move =='U':
                    y +=1
                if move == 'D':
                    y += 1
            return x == 0 and y == 0

复杂度:

chen445 commented 2 years ago

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        postion=[0,0]
        for move in moves:
            if move=="R":
                postion[0]+=1
            elif move == "L":
                postion[0]-=1
            elif move == "U":
                postion[1]+=1
            elif move == "D":
                postion[1]-=1
            else:
                return False
        if postion[0]==0 and postion[1]==0:
            return True
        else:
            return False

复杂度

Time: O(n)

Space: O(1)

cy-sues commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
        int a=0,b=0;
            for(int i=0;i < moves.length();i++){
                switch(moves.charAt(i)){
                    case 'U': 
                                a=a+1;
                                break;
                    case 'D': 
                                a=a-1;
                                break;
                    case 'L': 
                                b=b+1;
                                break;
                    case 'R': 
                                b=b-1;
                                break;
                }
            }
            if(a==0&&b==0)
                return true;
            else
                return false; 
    }
}
kkwu314 commented 2 years ago

思路

模拟,利用坐标(x,y)记录每次move后的坐标

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x,y = 0,0
        for move in moves:
            if move == "U":
                y+=1
            elif move == "D":
                y-=1
            elif move == "L":
                x+=1
            else:
                x-=1       
        return x==0 and y==0

复杂度

时间:O(N)

空间:O(1)

leungogogo commented 2 years ago

Simulation, time O(n), where n is the length of string, and space O(1).

class Solution {
    public boolean judgeCircle(String moves) {
        int n = moves.length();
        int[] pos = new int[2];

        for (int i = 0; i < n; ++i)
        {
            char ch = moves.charAt(i);
            if (ch == 'L') {
                pos[0]--;
            } else if (ch == 'R') {
                pos[0]++;
            } else if (ch == 'U') {
                pos[1]++;
            } else {
                pos[1]--;
            }
        }
        return pos[0] == 0 && pos[1] == 0;
    }
}
xbhog commented 2 years ago

657. 机器人能否返回原点

思路:

通过两个变量控制是否到达原点,开始想得是map,属实想复杂了;

Java代码段:

class Solution {
    public boolean judgeCircle(String moves) {
        char[] ch = moves.toCharArray();
        int x = 0,y =0;
        for(int i = 0; i < ch.length; i++){
            if(ch[i] == 'R') y++;
            if(ch[i] == 'L') y--;
            if(ch[i] == 'D') x++;
            if(ch[i] == 'U') x--;
        }
        if(x == 0 && y == 0) return  true;
        return false;
    }
}

复杂度分析:

时间复杂度:O(n)

空间复杂度:O(n);

ccslience commented 2 years ago
bool judgeCircle(string moves)
    {
        vector<int> info = {0, 0};
        for(int i = 0; i < moves.length(); i++)
        {
            if (moves[i] == 'U')
                info[0]++;
            else if(moves[i] == 'D')
                info[0]--;
            else if(moves[i] == 'L')
                info[1]++;
            else
                info[1]--;
        }
        if (info[0] == 0 && info[1] == 0)
            return 1;
        else
            return 0;
    }
m-z-w commented 2 years ago
var judgeCircle = function(moves) {
    let x = 0, y = 0
    for (let i = 0; i < moves.length; i++) {
        switch(moves[i]){
            case 'U':
                y++
                break
            case 'D':
                y--
                break
            case 'L':
                x--
                break
            case 'R':
                x++
                break
        }
    }
    if (x === 0 && y === 0) {
        return true
    }
    return false
};

时间:O(n) 空间:O(1)

ZoharZhu commented 2 years ago

代码

var judgeCircle = function(moves) {
    let x = 0, y = 0;
    for(let i of moves) {
        if(i == 'R') {
            x ++;
        } else if (i == "L") {
            x --;
        } else if (i == 'U') {
            y ++;
        } else {
            y --;
        }
    }
    return !x&&!y;
};

复杂度

TimmmYang commented 2 years ago

思路

使用两个变量记录每次移动后的横纵坐标位置。

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x, y = 0, 0
        for ch in moves:
            if ch == 'U':
                y += 1
            elif ch == 'D':
                y -= 1
            elif ch == 'L':
                x -= 1
            elif ch == 'R':
                x += 1
        return True if x == 0 and y == 0 else False

复杂度

时间:O(N) N为moves长度 空间:O(1)

mixtureve commented 2 years ago

思路

用横纵坐标 x, y 模拟

代码

Java Code:


class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        for (char move: moves.toCharArray()) {
            if (move == 'U') y--;
            else if (move == 'D') y++;
            else if (move == 'L') x--;
            else if (move == 'R') x++;
        }
        return x == 0 && y == 0;
    }
}

复杂度分析

令 n 为数组长度。

asterqian commented 2 years ago

思路

奇数次走路肯定走不回源点,以U和L作为基准,向这两个方向就加,否则就减,如果都为0则回到源点

代码

class Solution {
public:
    bool judgeCircle(string moves) {
        if (moves.size() % 2 == 1) return false;
        int U = 0;
        int L = 0;
        for (char c: moves) {
            if (c == 'U') {
                U++;
            } else if (c == 'D') {
                U--;
            } else if (c == 'L') {
                L++;
            } else if (c == 'R') {
                L--;
            }
        }
        return (U == 0 && L == 0);
    }
};

Time Complexity: O(N)

Space Complexity: O(1)

ginnydyy commented 2 years ago

Problem

https://leetcode.com/problems/robot-return-to-origin/

Notes

Solution

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0;
        int y = 0;
        for(int i = 0; i < moves.length(); i++){
            char move = moves.charAt(i);
            if(move == 'R'){
                x++;
            }else if(move == 'L'){
                x--;
            }else if(move == 'U'){
                y++;
            }else{
                y--;
            }
        }

        return x == 0 && y == 0;
    }
}

Complexity

RonghuanYou commented 2 years ago
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = y = 0
        for c in moves:
            if c == 'L':
                x -= 1
            elif c == 'R':
                x += 1
            elif c == 'U':
                y += 1
            elif c == 'D':
                y -= 1
        return x == 0 and y == 0
AnhTom2000 commented 2 years ago

思路

维护一个坐标,根据给的有效动作进行模拟坐标轴上的移动,最后判定坐标是否还在原点

代码:Java

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0;
        int y = 0;
        int len = moves.length();
        for(int i = 0; i < len;i++){
           switch(moves.charAt(i)){
             case 'U':{
               y++;
               break;
             }
             case 'D':{
               y--;
               break;
             }
             case 'L' : {
               x--;
               break;
             }
             case 'R' :{
               x++;
               break;
             }
           }
        }
        return x == 0 && y ==0 ;
    }
}

复杂度分析

时间复杂度:O(n)

空间复杂度:O(1)

标签

模拟

kennyxcao commented 2 years ago

657. Robot Return to Origin

Intuition

Code

/**
 * @param {string} moves
 * @return {boolean}
 */
const judgeCircle = function(moves) {
  let x = 0;
  let y = 0;
  for (const move of moves) {
    switch (move) {
      case 'L':
        x -= 1;
        break;
      case 'R':
        x += 1;
        break;
      case 'U':
        y += 1;
        break;
      case 'D':
        y -= 1;
        break;
    }
  }
  return x === 0 && y === 0;
};

Complexity Analysis

flame0409 commented 2 years ago

福利局

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        int length = moves.length();
        for (int i = 0; i < length; i++) {
            char move = moves.charAt(i);
            if (move == 'U') {
                y--;
            } else if (move == 'D') {
                y++;
            } else if (move == 'L') {
                x--;
            } else if (move == 'R') {
                x++;
            }
        }
        return x == 0 && y == 0;
    }
}

时间复杂度:O(n)

空间复杂度:O(1

lxy030988 commented 2 years ago

思路

代码 js

/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function (moves) {
  let x = 0,
    y = 0
  for (const move of moves) {
    switch (move) {
      case 'L':
        x--
        break
      case 'R':
        x++
        break
      case 'D':
        y--
        break
      default:
        y++
        break
    }
  }
  return x === 0 && y === 0
}

复杂度分析

guochiscoding commented 2 years ago
代码
var judgeCircle = function (moves) {
        if (moves == "") return true;
        if (moves.length < 2) return false;
        var lr = 0, ud = 0;
        for (let i = 0; i < moves.length; i++) {
                if (moves[i] == "R") {
                        lr++;
                } else if (moves[i] == "L") {
                        lr--;
                } else if (moves[i] == "U") {
                        ud++;
                } else if (moves[i] == "D") {
                        ud--;
                }
        }
        if (lr == 0 && ud == 0) return true;
        return false;
};
复杂度
思路

遍历每个动作,将上下 左右分为两组,分别用同一个变量代表行进长度

KennethAlgol commented 2 years ago

语言

java

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0;
        int y = 0;
        for (char move: moves.toCharArray()) {
            switch (move){
                case 'U':
                    y--;
                    break;
                case 'D':
                    y++;
                    break;
                case 'R':
                    x++;
                    break;
                case 'L':
                    x--;
                    break;
            }
        }
        return x == 0 && y == 0;
    }
}

复杂度分析

时间复杂度 O(n) 空间复杂度 O(1)

xjlgod commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
        int[] nums = new int[4];
        int len = moves.length();
        for (int i = 0; i < len; i++) {
            char temp = moves.charAt(i);
            switch (temp) {
                case 'U':
                    nums[0]++;
                    break;
                case 'D':
                    nums[1]++;
                    break;
                case 'L':
                    nums[2]++;
                    break;
                case 'R':
                    nums[3]++;
                    break;
            }
        }
        if (nums[0] != nums[1]) {
            return false;
        }
        if (nums[2] != nums[3]) {
            return false;
        }
        return true;
    }
}
ZJP1483469269 commented 2 years ago

思路

模拟

代码

class Solution {
public boolean judgeCircle(String moves) {
    int[] res = new int[2];
    for(int i=0;i<moves.length();i++){
        char c = moves.charAt(i);
        if(c=='U'){
            res[0]++;
        }else if(c=='D'){
            res[0]--;
        }else if(c=='L'){
            res[1]++;
        }else res[1]--;
    }
    if(res[0]==0&&res[1]==0)return true;
    return false;
}
}

复杂度分析

时间复杂度:O(n) 空间复杂度:O(1)

july-aha commented 2 years ago
var judgeCircle = function (moves) {
    let routeMap = {
        U: 1,
        D: -1,
        L: 1,
        R: -1
    }
    let coordinate = [0, 0]
    moves.split("").forEach((item) => {
        if (item === "U" || item === "D") {
            coordinate[0] += routeMap[item]
        }else{
            coordinate[1] += routeMap[item]
        }
    })
    return coordinate[0]===0 && coordinate[1] === 0
};

时间复杂度:O(N) 空间复杂度:O(1)

xyinghe commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
        if(moves == "") return true;
        else{
            int x = 0;
            int y = 0;
            int len = moves.length();
            for (int i = 0; i < len; i++) {
                char move = moves.charAt(i);
                if(move == 'U'){
                    y--;
                } else if (move == 'D') {
                    y++;
                } else if (move == 'L') {
                    x--;
                } else if (move == 'R') {
                    x++;
                }
            }
        return x == 0 && y == 0;
    }
}
}
AutumnDeSea commented 2 years ago
/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function (moves) {
  let x = 0,
    y = 0
  for (const move of moves) {
    switch (move) {
      case 'L':
        x--
        break
      case 'R':
        x++
        break
      case 'D':
        y--
        break
      default:
        y++
        break
    }
  }
  return x === 0 && y === 0
}
newbeenoob commented 2 years ago

思路


简单模拟,分别构建 u , d , l , r 四个移动指令与 x , y 方向上的偏移量的映射关系,遍历 moves ,最后判断 x , y 是否还是0即可。

代码:JavaScript

var judgeCircle = function(moves) {

    let x = 0;
    let y = 0;

    const offsetX = {
        'U' : 0,
        'D' : 0,
        'R' : 1,
        'L' : -1
    };

    const offsetY = {
        'U' : 1,
        'D' : -1,
        'R' : 0,
        'L' : 0
    };

    for(const move of moves){
        x += offsetX[move];
        y += offsetY[move];
    }

    return x === 0 && y === 0;
};

复杂度分析


标签


模拟

BreezePython commented 2 years ago

思路

哈希表 统计四个方位分别移动的步数,然后计算结果是否回到原点

代码

class Solution:
    def judgeCircle(self, moves):
        distance = {"L": [-1, 0], "R": [1, 0], "U": [0, 1], "D": [0, -1]}
        x = y = 0
        for k, v in Counter(moves).items():
            x += distance[k][0] * v
            y += distance[k][1] * v
        return x == y == 0

复杂度

hwpanda commented 2 years ago
var judgeCircle = function(moves) {
  let x = 0, y = 0;

  for(let i = 0; i < moves.length; i++) {
      x += (moves[i] === 'R');
      x -= (moves[i] === 'L');
      y += (moves[i] === 'D');
      y -= (moves[i] === 'U');   
  }

  return x === 0 && y === 0;
};
LareinaWei commented 2 years ago

Thinking

Brute force.

Code

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        pos = [0,0]
        for i in moves:
            if i == "R":
                pos[1] +=1
            if i == "L":
                pos[1] -=1
            if i == "U":
                pos[0] +=1
            if i == "D":
                pos[0] -=1

        return pos == [0,0]

Complexity

Time complexity: O(n). Space complexity: O(1).

comst007 commented 2 years ago

657. 机器人能否返回原点


思路

模拟
定义两个变量x, y分别代表机器人的横坐标和纵坐标 初始 x = 0y = 0,机器人每向左走一步 --y, 每向右走一步 ++y
每向上走一步 --x,向下走一步 ++x。 最后判断是否满足x == 0 && y== 0即可。

代码

class Solution {
public:
    bool judgeCircle(string moves) {
        int x, y;
        x = 0;
        y = 0;
        for(auto& cc: moves){
            if(cc == 'R'){
                ++ y;
                continue;
            }
            if(cc == 'L'){
                -- y;
                continue;
            }
            if(cc == 'U'){

                -- x;
                continue;
            }
            if(cc == 'D'){
                ++ x;
                continue;
            }
        }

        return x == 0 && y == 0;
    }
};

复杂度分析

n为字符串长度

AstrKing commented 2 years ago

32、机器人能否返回原点

思路

我们只需按指令模拟机器人移动的坐标即可。起始时机器人的坐标为 (0,0)(0,0),在遍历完所有指令并对机器人进行移动之后,判断机器人的坐标是否为 (0,0)(0,0) 即可。

代码

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        int length = moves.length();
        for (int i = 0; i < length; i++) {
            char move = moves.charAt(i);
            if (move == 'U') {
                y--;
            } else if (move == 'D') {
                y++;
            } else if (move == 'L') {
                x--;
            } else if (move == 'R') {
                x++;
            }
        }
        return x == 0 && y == 0;
    }
}

时间复杂度:O(n)

空间复杂度:O(1)

jinmenghan commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        int length = moves.length();
        for (int i = 0; i < length; i++) {
            char move = moves.charAt(i);
            if (move == 'U') {
                y--;
            } else if (move == 'D') {
                y++;
            } else if (move == 'L') {
                x--;
            } else if (move == 'R') {
                x++;
            }
        }
        return x == 0 && y == 0;
    }
}
whgsh commented 2 years ago

思路

根据移动顺序对坐标进行修改,看最后是否能得到(0,0)

代码

Python3 Code:

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = y = 0
        for move in moves:
            if move == 'R': x += 1
            if move == 'L': x -= 1
            if move == 'U': y += 1
            if move == 'D': y -= 1

        return x == 0 and y == 0

复杂度分析

famine330 commented 2 years ago

思路

模拟,初始位置设定为(0,0),遍历操作,R(x += 1),L(x -= 1),U(y += 1)和 D(y -= 1),如果最后回到(0,0)返回True,否则返回False

代码:

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = y = 0
        for i in moves:
            if i == 'L':
                x -= 1
            elif i == 'R':
                x += 1
            elif i == "U":
                y += 1
            else:
                y -= 1
        return x == y == 0

复杂度分析:

时间复杂度:O(N),N为操作数 空间复杂度:O(1)