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,因为它在移动结束时没有返回原点。

yanglr commented 2 years ago

思路

模拟法

定义一个初始坐标(x, y), 每次从moves数组读入一个字符, 根据具体反向进行一次x或y的增减。 看循环结束时, 是否能使 x == 0 且 y ==0 。

代码

实现语言: C++

class Solution {
public:
    bool judgeCircle(string moves) {
        int x = 0;
        int y = 0;
        for (const auto& move : moves)
        {
            switch (move)
            {
                case 'U':
                    y--;
                    break;
                case 'D':
                    y++;
                    break;
                case 'R':
                    x++;
                    break;
                case 'L':
                    x--;
                    break;
                }
        }
        return x == 0 && y == 0;
    }
};

复杂度分析

BpointA commented 2 years ago

思路

设置x y坐标,模拟即可

Python3代码

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

        return x==0 and y==0

复杂度

时间复杂度:O(n),遍历s

空间复杂度:O(1),x和y

xj-yan commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;

        for (char c : moves.toCharArray()){
            if (c == 'U') y++;
            else if (c == 'D') y--;
            else if (c == 'L') x--;
            else x++;
        }
        return x == 0 && y == 0;
    }
}

Time Complexity: O(n), Space Complexity: O(1)

yingliucreates commented 2 years ago

link:

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

代码 Javascript

const judgeCircle = function (moves) {
  const map = new Map();
  const movesArr = moves.split("");
  for (let el of movesArr) {
    map.has(el) ? map.set(el, map.get(el) + 1) : map.set(el, 1);
  }
  let udEval = map.get("U") === map.get("D") ? true : false;
  let lrEval = map.get("L") === map.get("R") ? true : false;
  return udEval && lrEval;
};

复杂度分析

time & space O(n)

wangzehan123 commented 2 years ago

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

复杂度分析

令 n 为数组长度。

kidexp commented 2 years ago

thoughts

计算水平和竖直方向的move,往左就水平+1,往右水平-1,往上竖直+1,往下竖直-1

最后判断这两个是不是0

code

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

complexity

Time O(n)

Space O(1)

chenming-cao commented 2 years ago

解题思路

模拟。最后看返回的坐标是否为(0, 0)。

代码

class Solution {
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        int length = moves.length();
        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;
    }
}

复杂度分析

q815101630 commented 2 years ago

思路:

入门的模拟题,模拟水平和垂直坐标系,机器人向对应方向移动时,对应的坐标值加1,最后判断 机器人回到原点没有即可

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

时间,遍历了整个数组: O(n) 空间,2个常数: O(1)

thinkfurther commented 2 years ago

思路

由于这里只有两个维度,于是用复数来表示移动比较方便。按照方向移动后,判断最后是否为0.

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        position = {'U':1, 
                    'D': -1,
                    'L': complex(0,-1),
                    'R': complex(0,1),}

        current_position = complex(0,0)

        for move in moves:
            direction = position[move]
            current_position += direction

        if current_position == complex(0,0):
            return True
        else:
            return False

复杂度

时间复杂度 :O(N)

空间复杂度:O(1)

ysy0707 commented 2 years ago

思路:按照题目的意思模拟

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

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

pophy commented 2 years ago

思路

Java Code

class Solution {    
    public boolean judgeCircle(String moves) {
        Position startPos = new Position(0, 0);
        Position endPos = startPos;
        for (char d : moves.toCharArray()) {
            endPos = move(endPos,d);
        }
        return startPos.equals(endPos);
    }

    public Position move(Position pos, char direction) {
        int x = pos.x;
        int y = pos.y;
        switch (direction) {
            case 'U':
                x += -1;
                break;
            case 'D':
                x += 1;
                break;
            case 'L':
                y += -1;
                break;
            case 'R':
                y += 1;
                break;
        }
        return new Position(x, y);
    }

    private class Position {
        int x;
        int y;

        public Position(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            Position position = (Position) o;
            return x == position.x && y == position.y;
        }
    }
}

时间&空间

jsu-arch commented 2 years ago

思路

按照题目来模拟


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

Time Complexity

Time: O(n) space: O(1) no extra spaces needed

ZacheryCao commented 2 years ago

Solution

Stimulate the moves according to the instruction. Then check whether the end is [0, 0]

Code(python)

from operator import add
class Solution:
    def judgeCircle(self, m: str) -> bool:
        moves = {"U":[0, 1], "D":[0, -1], "L":[-1, 0], "R":[1, 0]}
        start = [0, 0]
        for i in m:
            start = list(map(add, start, moves[i]))
        return start == [0, 0]

Complexity:

Time: O(n). n is the length of the instruction Space: O(1)

laofuWF commented 2 years ago
# track x, y coordinate
# return at 0, 0 if x == 0 and y == 0
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        if not moves:
            return True

        x = 0
        y = 0

        for m in moves:
            if m == "U":
                y += 1
            elif m == "D":
                y -= 1
            elif m == "L":
                x -= 1
            else:
                x += 1

        return x == 0 and y == 0
bingyingchu commented 2 years ago

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

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

Time: O(n)/Space: O(1)
shuichen17 commented 2 years ago
var judgeCircle = function(moves) {
    let countR = 0;
    let countL = 0;
    let countU = 0;
    let countD = 0;
    for (let i = 0; i < moves.length; i++) {
        if (moves[i] === 'R') {
            countR++;
        } else if (moves[i] === 'L') {
            countL++;
        } else if (moves[i] === 'U') {
            countU++;
        } else if (moves[i] === 'D') {
            countD++;
        } 
    }
    return countR === countL && countU === countD ? true : false;
};
JiangyanLiNEU commented 2 years ago

Runtime = O(n), Space = O(1)

JavaScript
var judgeCircle = function(moves) {
    let left = 0;
    let up = 0;

    for (move of moves){
        switch (move){
            case 'L': 
                left++;
                break;
            case 'R': 
                left--;
                break;
            case "U": 
                up++;
                break;
            case 'D': 
                up--;
                break;
        };
    };
    return left==0 && up==0;
};
Python
class Solution(object):
    def judgeCircle(self, moves):
        left = 0
        up = 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
littlemoon-zh commented 2 years ago

day 32

657. Robot Return to Origin

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

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

james20141606 commented 2 years ago

Day 32: 657. Robot Return to Origin (string, simulation)

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

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        if len(moves) % 2: return False
        count = Counter([i for i in moves])
        return count['L']==count['R'] and count['U']==count['D']
Menglin-l commented 2 years ago

思路:

模拟横纵坐标的移动


代码部分:

class Solution {

    public boolean judgeCircle(String moves) {
        if (moves.length() == 0) return false;

        int[] pos = new int[]{0, 0};
        for (int i = 0; i < moves.length(); i ++) {

            char temp = moves.charAt(i);

            if (temp == 'U') pos[1] ++;
            else if (temp == 'D') pos[1] --;
            else if (temp == 'L') pos[0] --;
            else if (temp == 'R') pos[0] ++;

        }

        return pos[0] == 0 && pos[1] == 0;
    }
}

复杂度:

Time: O(N),遍历了整个字符串,N为moves的长度

Space: O(1)

siyuelee commented 2 years ago
class Solution(object):
    def judgeCircle(self, moves):
        x = 0
        y = 0
        for m in moves:
            if m == 'R': x += 1
            if m == 'L': x -= 1
            if m == 'U': y += 1
            if m == 'D': y -= 1
        if x == 0 and y == 0:
            return True
        else:
            return False

T: n S: 1

leo173701 commented 2 years ago

思路:没啥思路,

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

O(n), O(1).

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        c = Counter(moves)
        return c['U'] == c['D'] and c['L'] == c['R']
        def move(x, y, m):
            if m == "U":
                return (x, y+1)
            if m == "D":
                return (x, y-1)
            if m == "L":
                return (x-1, y)
            if m == "R":
                return (x+1, y)
        x, y = 0, 0
        for m in moves:
            x, y = move(x, y, m)
        return x == 0 and y == 0
chang-you commented 2 years ago

Ideas

simulation

Java Code

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

        for (char ch : moves.toCharArray()) {
            if (ch == 'U') y++;
            else if (ch == 'D') y--;
            else if (ch == 'R') x++;
            else if (ch == 'L') x--;
        }
        return x == 0 && y == 0;
    }
}

Complexity

Time = O(N): iterate over the whole string
Space = O(1)

nonevsnull commented 2 years ago

思路

AC

代码

class Solution {
    public boolean judgeCircle(String moves) {
        int[] directions = new int[4];

        for(int i = 0;i < moves.length();i++){
            char cur = moves.charAt(i);
            switch (cur) {
                case 'U': 
                    directions[0]++;
                    break;
                case 'R': 
                    directions[1]++;
                    break;
                case 'D': 
                    directions[2]++;
                    break;
                default:
                    directions[3]++;
            }
        }

        return directions[0] == directions[2] && directions[1] == directions[3];
    }
}

复杂度

time: O(N) space: O(1),有限个元素的array依旧是常数级

CoreJa commented 2 years ago

思路

简单题,给个变量表示坐标,各个方向对应加减即可

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        long = 0
        lat = 0
        for move in moves:
            if move == 'U':
                lat += 1
            elif move == 'D':
                lat -= 1
            elif move == 'L':
                long -= 1
            elif move == 'R':
                long += 1
        return bool(not (long or lat))
mmboxmm commented 2 years ago

思路

san and compare

代码

fun judgeCircle(moves: String): Boolean {
  val map = moves.asSequence().groupingBy { it }.eachCount()
  return map.getOrDefault('U', 0) == map.getOrDefault('D', 0) &&
    map.getOrDefault('L', 0) == map.getOrDefault('R', 0)
}

复杂度

AgathaWang commented 2 years ago
class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        if moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R'):
            return True
        return False

time complexity: O(N)

st2yang commented 2 years ago

思路

代码

复杂度

ychen8777 commented 2 years ago

思路

x, y分别表示横纵坐标,遍历moves增减

代码

class Solution {
    public boolean judgeCircle(String moves) {

        int x = 0, y = 0;
        // Map<Character, int[]> movement = new HashMap<>();
        // movement.put('R', new int[]{1,0});
        // movement.put('D', new int[]{0,1});
        // movement.put('L', new int[]{-1,0});
        // movement.put('U', new int[]{0,-1});

        for(int i = 0; i < moves.length(); i++){
            char c = moves.charAt(i);
            switch(c) {
                case 'R':
                    x++;
                    break;
                case 'L':
                    x--;
                    break;
                case 'U':
                    y--;
                    break;
                case 'D':
                    y++;
                    break;
                }
            }

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

    }
}

复杂度

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

bolunzhang2021 commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
     boolean flag=false;
     int x=0,y=0;
    for(char move : moves.toCharArray())
    {
        if (move == 'R') x += 1;
        if (move == 'L') x -= 1;
        if (move == 'U') y += 1;
        if (move == 'D') y -= 1;
    }
    if(x==0&&y==0)
    flag=true;
    return flag;
    }
}

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

skinnyh commented 2 years ago

Note

Solution 1 - Simulation

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

Time complexity: O(N)

Space complexity: O(1)

Solution 2 - Counter

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

Time complexity: O(N)

Space complexity: O(1)

falconruo commented 2 years ago

思路:

方法一、模拟法, 是否回到原点与起始位置无关,只与移动的路径有关(string moves),使用两个v, l变量存放水平和垂直的移动,每次一步

复杂度分析:

  1. 时间复杂度: O(n), 其中 n是移动的步数moves的长度
  2. 空间复杂度: O(1)

代码(C++):

class Solution {
public:
    bool judgeCircle(string moves) {
        int l = 0, v = 0;

        for (auto s : moves) {
            if (s == 'U')
                v++;
            else if (s == 'D')
                v--;
            else if (s == 'L')
                l++;
            else
                l--;
        }

        return l == 0 && v == 0;
    }
};
weichuliao commented 2 years ago
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        if len(moves) % 2: return False
        x = y = 0
        for move in moves:
            if move == 'L':
                x -= 1
            elif move == 'R':
                x += 1
            elif move == 'U':
                y += 1
            elif move == 'D':
                y -= 1
        print (x, y)
        return x==0 and y==0
zhangzz2015 commented 2 years ago

思路

关键点

代码

C++ Code:


class Solution {
public:
    bool judgeCircle(string moves) {

        int x=0; 
        int 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
            {
                x++;
            }
        }
        return x==0 && y==0; 
    }
};
tongxw commented 2 years ago

思路

直接模拟四个方向,最后判断坐标x,y == 0,0

代码

class Solution {
    public boolean judgeCircle(String moves) {
        Map<Character, int[]> directions = new HashMap<>() {
            {
                put('U', new int[]{0, -1});
                put('D', new int[]{0, 1});
                put('L', new int[]{-1, 0});
                put('R', new int[]{1, 0});
            }
        };

        int x = 0;
        int y = 0;
        for (char c : moves.toCharArray()) {
            int[] dir = directions.get(c);
            x += dir[0];
            y += dir[1];
        }

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

TC: O(len(moves)) SC: O(1)

yuxiangdev commented 2 years ago

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

Jackielj commented 2 years ago

机器人能否回到原点

直接模拟直角坐标系, 最终检测x 和 y的值是否回到原点;

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

时空复杂度

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

a244629128 commented 2 years ago

/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function(moves) {
    let x = 0;
    let y = 0;
    for(let e of moves){
        if(e === 'L'){
            x--;
        }else if (e === 'R'){
            x++;
        }else if (e === 'U'){
            y++;
        }else if (e === 'D'){
            y--;
        }
    }
    return x === 0 && y === 0; 
};
// time O(n)
// space O(1)
simonsayshi commented 2 years ago
class Solution {
public:
    bool judgeCircle(string moves) {
        int horizontal = 0;
        int vertical = 0;
        for(int i = 0 ; i < moves.size();i++) {
            if(moves[i] == 'U')
                horizontal++;
            if(moves[i] == 'D')
                horizontal--;
            if(moves[i] == 'R')
                vertical++;
            if(moves[i] == 'L')
                vertical--;
        }
        return (horizontal == 0) && (vertical == 0);
    }
};
learning-go123 commented 2 years ago

思路

代码

Go Code:


func judgeCircle(moves string) bool {
    x, y := 0, 0
    for _, move := range moves {
        str := string(move)
        switch str {
        case "U":
            x++
        case "D":
            x--
        case "R":
            y++
        case "L":
            y--
        }
    }

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

复杂度分析

令 n 为数组长度。

ghost commented 2 years ago

题目

  1. Robot Return to Origin

思路

Move the robot and see

代码


class Solution:
    def judgeCircle(self, moves: str) -> bool:

        x = y = 0

        for m in moves:
            if m == 'U': y+=1
            elif m == 'D': y-=1
            elif m == 'L': x-=1
            else: x+=1

        return x == 0 and y == 0

复杂度

Space: O(1) Time: O(N)

freesan44 commented 2 years ago

思路

遍历进行运算

代码

Python3 Code:


class Solution:
    def judgeCircle(self, moves: str) -> bool:
        RL,UD = 0,0
        for i in moves:
            if i == "R":
                RL += 1
            elif i == "L":
                RL -= 1
            elif i == "U":
                UD += 1
            elif i == "D":
                UD -= 1
        return RL == 0 and UD == 0

复杂度分析

令 n 为数组长度。

guangsizhongbin commented 2 years ago
class Solution {
    public boolean judgeCircle(String moves) {
                // 上下方向以上为+,以下为-, 左右方向以左为+, 以右为-
        int leftAndRight = 0;
        int upAndDown = 0;

        for (int i = 0; i < moves.length(); i++) {
//            System.out.println("第i个位置是" + moves.charAt(i));

            char currentChar = moves.charAt(i);
            switch (currentChar){
                case 'U':
                    upAndDown ++;
                    break;
                case 'D':
                    upAndDown --;
                    break;
                case 'L':
                    leftAndRight ++;
                    break;
                case 'R':
                    leftAndRight --;
                    break;
            }

//            System.out.println("leftAndRight:" + leftAndRight);
//            System.out.println("upAndDown:" + upAndDown);
        }

        if(leftAndRight == 0 && upAndDown == 0){
           return true;
        }

        return false;
    }

}
carsonlin9996 commented 2 years ago
  1. x,y 最终坐标回到0,0

class Solution {
    public boolean judgeCircle(String moves) {

        int dX = 0;
        int dY = 0;

        for (int i = 0; i < moves.length(); i++) {
            char c = moves.charAt(i);

            switch(c) {
                case 'U' : dY++; break;
                case 'D' : dY--; break;
                case 'L' : dX++; break;
                case 'R' : dX--; break;
            }
        } 
        if (dX == 0 && dY == 0) {
            return true;
        } 
        return false;
    }
}

2. 哈希表统计坐标, 上下步数一致, 左右步数一致
class Solution {
    public boolean judgeCircle(String moves) {

        Map<Character, Integer> stepMap = new HashMap<>();

        String dir = "UDLR";

        for (int i = 0; i < 4; i++) {
            stepMap.put(dir.charAt(i), 0);
        }

        for (int i = 0; i < moves.length(); i++) {        
            stepMap.put(moves.charAt(i), stepMap.get(moves.charAt(i)) + 1);
        }

        if (stepMap.get('L').equals(stepMap.get('R')) && stepMap.get('U').equals(stepMap.get('D'))) {
            return true;
        }
        return false; 
    }
}
XinnXuu commented 2 years ago

代码

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

复杂度分析

ningli12 commented 2 years ago

变量表示坐标X, Y,各个方向对应加减, 返回坐标X, Y 是否为0

代码

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

复杂度分析

Francis-xsc commented 2 years ago

思路

用两个变量分别表示水平坐标和垂直坐标 判断移动后位置是否在原点

代码


class Solution {
public:
    bool judgeCircle(string moves) {
        int h=0,v=0;
        for(auto x:moves)
        {
            if(x=='R')
                h++;
            else if(x=='L')
                h--;
            else if(x=='U')
                v++;
            else if(x=='D')
                v--;
        }
        return h==0&&v==0;
    }
};

复杂度分析

yan0327 commented 2 years ago

思路: 一开始本能用哈希表,后面发现空间复杂度太多了。 一开始用四个if,果然还是switch更快一些

func judgeCircle(moves string) bool {
    x,y:=0,0
    for _,c := range moves{
        switch c{
            case 'U':
            y--
            case 'D':
            y++
            case 'L':
            x--
            case 'R':
            x++
       }
    }

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

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

zol013 commented 2 years ago

哈希表记录方向 Python 3 code

class Solution:
    def judgeCircle(self, moves: str) -> bool:

        position = (0, 0)
        movements = {'U':(0,1), 'D':(0, -1), 'L':(-1, 0), 'R':(1, 0)}

        for direction in moves:
            position = tuple(map(lambda x, y: x + y, position, movements[direction]))

        return position == (0, 0)

Time Complexity: O(N) Space Complexity: O(1)