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

EggEggLiu commented 2 years ago

代码

class Solution {
public:
    bool judgeCircle(string moves) {
        int cnt[4] = {};
        for (char c : moves) {
            switch (c) {
                case 'U':
                    ++cnt[0];
                    break;
                case 'R':
                    ++cnt[1];
                    break;
                case 'D':
                    ++cnt[2];
                    break;
                case 'L':
                    ++cnt[3];
                    break;
            }
        }
        if (cnt[0] == cnt[2] && cnt[1] == cnt[3]) {
            return true;
        }
        return false;
    }
};

复杂度

时间 O(n)

空间 O(1)

Weisday commented 2 years ago

代码

class Solution {
    public boolean judgeCircle(String moves) {
        int x;
        int y;
        int len;
        int i;
        char tmp;

        x = 0;
        y = 0;
        len = moves.length();
        for (i = 0; i < len; i++)
        {
            tmp = moves.charAt(i);
            if (tmp == 'R')
                x++;
            else if (tmp == 'L')
                x--;
            else if (tmp == 'U')
                y++;
            else if(tmp == 'D')
                y--;
        }

        return (x == 0 && y == 0);

    }
}

复杂度

时间复杂度O(n)

空间复杂度 O(1)

MissNanLan commented 2 years ago
/**
 * @param {string} moves
 * @return {boolean}
 */
 var judgeCircle = function(moves) {
     let x=0,y=0
    for(let i=0;i<moves.length;i++){
        let s = moves.charAt(i)
        switch(s){
            case 'U': y++; break
            case 'D': y--;break
            case 'L': x--;break
            default : x++
        }

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

时间复杂度:O(n)

空间复杂度:O(1)

ymwang-2020 commented 2 years ago

思路

遍历字符修改坐标,最后进行判断

代码

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

复杂度分析

o(len(str)) o(1)

last-Battle commented 2 years ago

思路

关键点

代码

C++ Code:


class Solution {
public:
    bool judgeCircle(string moves) {
        int res = 0;
        for (auto& s : moves) {
            if (s == 'R') {
                res += 1;
            } else if (s == 'L') {
                res -= 1;
            } else if (s == 'U') {
                res += 3;
            } else if (s == 'D') {
                res -= 3;
            }
        }

        return res == 0;
    }
};

复杂度分析

令 n 为字符串长度。

itsjacob commented 2 years ago

Intuition

Implementation

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

Complexity

babbomax98 commented 2 years ago

思路

当为L时,需要将横坐标减1,为U时将纵坐标减1,为R时将横坐标加1,为D时将纵坐标加1

代码

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);
            switch(move){
                case 'L':  x--;break;
                case 'U':  y--;break;
                case 'R':  x++;break;
                case 'D':  y++;break;
            }
        }
        return x == 0 && y == 0;
    }
}

复杂度分析

时间复杂度:O(n)

kbfx1234 commented 2 years ago

657. 机器人能否返回原点

// 10-11 cpp 模拟
class Solution {
public:
    bool judgeCircle(string moves) {
        int x = 0, y = 0;
        int n = moves.size();
        for (int i = 0; i < n; i++) {
            if (moves[i] == 'L') x += 1;
            else if (moves[i] == 'R') x -= 1;
            else if (moves[i] == 'U') y += 1;
            else y -= 1;
         }
         return (x == 0) && (y == 0);
    }
};
Lydia61 commented 2 years ago

机器人能否返回原点

思路

代码

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

        for m in moves:
            position += move_map[m]

        return not position

复杂度分析

zszs97 commented 2 years ago

开始刷题

题目简介

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

题目思路

题目代码

代码块

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

复杂度

Laurence-try commented 2 years ago

思路

直接模拟

代码

使用语言:Python3

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        loc = [0, 0]
        for m in moves:
            if m == 'U':
                loc[1] += 1
            if m == 'D':
                loc[1] -= 1
            if m == 'R':
                loc[0] += 1
            if m == 'L':
                loc[0] -= 1
        if loc[0] == 0 and loc[1] == 0:
            return True
        return False 

复杂度分析 时间复杂度:O(n), n is the length of moves string 空间复杂度:O(1)

yibenxiao commented 2 years ago

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

思路

两个变量代表垂直和水平,最后判断是否为零

代码

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        length = len(moves)
        lever,verticality = 0, 0
        for i in range(length):
            if moves[i] == 'U':
                verticality+=1
            if moves[i] == 'D':
                verticality-=1
            if moves[i] == 'L':
                lever-=1
            if moves[i] == 'R':
                lever+=1

        if  lever == 0 and verticality == 0:
            return True
        return False

复杂度

时间复杂度:O(N)

空间复杂度:O(1)

peteruixi commented 2 years ago

Approach

建立起点, 和每个操作对应的坐标变化, 最后判断最终坐标等于0,0

Code

def judgeCircle(self, moves: str) -> bool:
        dic = {'U':[0,1],'L':[-1,0],'R':[1,0],'D':[0,-1]}
        origin = [0,0]
        for move in moves:
            origin[0]+=dic[move][0]
            origin[1]+=dic[move][1]
        return origin[0] == 0 and origin[1]==0

Complexity

HWFrankFung commented 2 years ago

Codes

var judgeCircle = function(moves) {
    var move = {
        U : 0,
        D : 0,
        L : 0,
        R : 0
    }
    for(var i=0;i<moves.length;++i){
        move[moves[i]] ++
    }
    if(move.U-move.D == 0 && move.L-move.R == 0){
        return true
    }else{
        return false
    }
};
LAGRANGIST commented 2 years ago

class Solution { public: bool judgeCircle(string moves) { int n = moves.size(); if(n == 0)return true; int x = 0; int y = 0; for(int i = 0;i<= n;i++) { if(moves[i] == 'U')y++; else if(moves[i] == 'D')y--; else if(moves[i] == 'L')x--; else if(moves[i] == 'R')x++; else std::cerr<<"Invaild Input"; } if(x!=0||y!=0)return false; else return true; } };

YuanWenLai commented 2 years ago

### 思路

​ 模拟

### 代码

/**
 * @param {string} moves
 * @return {boolean}
 */
 var judgeCircle = function(moves) {
    let moveStyle = {
        U: 0,
        D: 0,
        R: 0,
        L: 0
    }

    for(let i=0;i<moves.length;i++) {
        moveStyle[moves[i]]++
    }
    if(moveStyle['U']-moveStyle['D'] == 0 && moveStyle['R']-moveStyle["L"] ==0) {
        return true
    }else {
        return false
    }
};

*复杂度分析*

- 时间复杂度:O(N)

- 空间复杂度:O(1)

mokrs commented 2 years ago
bool judgeCircle(string moves) {
    int x = 0, y = 0;
    for (char ch : moves){
        switch (ch){
            case 'R':
                x -= 1;
                break;
            case 'L':
                x += 1;
                break;
            case 'U':
                y += 1;
                break;
            case 'D':
                y -= 1;
                break;
        }
    }
    return x == 0 && y == 0;
}

复杂度

max-qaq commented 2 years ago
class Solution {
    int [] x = new int[]{0,-1,0,1};
    int [] y = new int[]{1,0,-1,0};
    public boolean judgeCircle(String moves) {
        Map<Character,Integer> map = new HashMap();
        map.put('U',0);
        map.put('L',1);
        map.put('D',2);
        map.put('R',3);
        int xpos = 0;
        int ypos = 0;
        for(Character ch : moves.toCharArray()){
            xpos += x[map.get(ch)];
            ypos += y[map.get(ch)];
        }
        if(xpos == 0 && ypos == 0) return true;
        return false;
    }
}

还是比较简单的,easy的题还是能拿下

Gjts commented 2 years ago

语言 CSharp

思路:根据题意coding

code

public bool JudgeCircle(string moves) {
        int x = 0;
        int y = 0;
        foreach (char c in moves) {
            if (c == 'U') y++;
            if (c == 'D') y--;
            if (c == 'L') x++;
            if (c == 'R') x--;
        }
        return x == 0 && y == 0;
    }
JinhMa 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; } }

Maschinist-LZY commented 2 years ago

思路

模拟

关键点

代码

C++ Code:


class Solution {
public:
    bool judgeCircle(string moves) {
        int x=0,y=0;
        for(auto ac:moves){
            if(ac=='U')y+=1;
            if(ac=='D')y-=1;
            if(ac=='L')x-=1;
            if(ac=='R')x+=1;
        }
        if(x==0 && y==0)return true;
        return false;
    }
};

复杂度分析

令 n 为数组长度。

ymkymk commented 2 years ago

思路

正常解法

代码

``

class Solution {
    public boolean judgeCircle(String moves) {
        int m = 0;
        int n = 0;
        if (moves == null || moves.trim() == "") {
            return true;
        }

        char[] chars = moves.trim().toCharArray();
        int len = chars.length;
        while (len-- > 0) {
            if ('R' == chars[len]) {
                m++;
            } else if ('L' == chars[len]) {
                m--;
            } else if ('U' == chars[len]) {
                n++;
            } else if ('D' == chars[len]) {
                n--;
            }
        }

        if (m == 0 && n == 0) {
            return true;
        }

        return false;
    }
}

复杂度分析

时间复杂度:O(n)

空间复杂度:O(1)

machuangmr commented 2 years ago

题目:657. 机器人能否返回原点

思路

JAYWX 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
for123s commented 2 years ago

代码

C++ Code:


class Solution {
public:
    bool judgeCircle(string moves) {
        int flag1=0, flag2=0;
        for(int i=0;i<moves.size();++i)
            switch(moves[i])
            {
                case 'U': flag1++ ; break ;
                case 'D': flag1-- ; break ;
                case 'L': flag2-- ; break ;
                case 'R': flag2++ ; break ;
                default: break ;
            }
        return !(flag1|flag2) ;
    }
};

复杂度分析

令 n 为数组长度。

carinSkyrim commented 2 years ago

思路

代码

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """

        location_dict = {'R':(1, 0), 'L':(-1, 0), 'U': (0, 1), 'D': (0, -1)}
        startx = 0
        starty = 0
        for l in moves:
            startx += location_dict[l][0]
            starty += location_dict[l][1]
        return not startx and not starty

复杂度

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

yj9676 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;
    }
}
zyMacro commented 2 years ago
var judgeCircle = function(moves) {
  const map = new Map();
    const vertical = 'vertical';
    const horizontal = 'horizontal';
    map.set(vertical, 0);
    map.set(horizontal, 0);
    const arr = moves.split('');
    arr.forEach((item, index) => {
        if(item === 'R') {
            map.set(vertical, map.get(vertical) + 1);
        } else if(item === 'L') {
            map.set(vertical, map.get(vertical) - 1);
        } else if(item === 'U') {
            map.set(horizontal, map.get(horizontal) + 1);
        } else {
            map.set(horizontal, map.get(horizontal) - 1);
        }
    })
    if(map.get(vertical) === 0 && map.get(horizontal) === 0) {
        return true;
    } else {
        return false;
    }
};
xingkong1994 commented 2 years ago

思路

当字符串中 U 和 D的个数相同 并且 R和L的个数相同时, 则表示能回到原点。

代码

class Solution {
public:
    bool judgeCircle(string moves) {
        if (moves.empty())  return true;
        map<char, int> mymap;
        for (int i = 0; i < moves.size(); i++) {
            mymap[moves[i]]++;
        }
        if (mymap['R'] == mymap['L'] && mymap['U'] == mymap['D']) {
            return true;
        }
        return false;
    }
};
heyqz commented 2 years ago
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = y = 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

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

BadCoderChou commented 2 years ago
class Solution {
    public int[] sortItems(int n, int m, int[] group, List<List<Integer>> beforeItems) {

        Map<Integer, Set<Integer>> groupGraph = new HashMap<>();
        Map<Integer, Integer> indegreeGroup = new HashMap<>();

        int increment = 0;
        for(int i = 0 ; i < group.length; i++){
            if(group[i]==-1){
                group[i] = group[i] + increment;
                increment = increment-2;
            }
            groupGraph.put(group[i], new HashSet<Integer>());
        }

        Map<Integer, Set<Integer>> itemGraph = new HashMap<>();
        Map<Integer, Integer> indegreeItem = new HashMap<>();

        for(int i = 0; i < n ; i++)
            itemGraph.put(i, new HashSet<Integer>());

        for(int i = 0 ; i < beforeItems.size(); i++){
            List<Integer> l = beforeItems.get(i);
            for(int item : l){
                itemGraph.get(item).add(i);
                indegreeItem.put(i, indegreeItem.getOrDefault(i,0)+1);

                int group1 = group[item];
                int group2 = group[i];

                if(group1!=group2 && groupGraph.get(group1).add(group2)){
                    indegreeGroup.put(group2, indegreeGroup.getOrDefault(group2,0)+1);
                }
            }
        }

        List<Integer> itemOrdering = topoSort(itemGraph, indegreeItem, n);
        List<Integer> groupOrdering = topoSort(groupGraph, indegreeGroup, groupGraph.size());

        if(itemOrdering.size()==0 || groupOrdering.size()==0) return new int[0];

        Map<Integer, List<Integer>> map = new HashMap<>();
        for(int item : itemOrdering){
            int grp = group[item];
            map.putIfAbsent(grp, new ArrayList<>());
            map.get(grp).add(item);
        }

        int[] res = new int[n];
        int i=0;
        for(int grp : groupOrdering){
            List<Integer> l = map.get(grp);
            for(int item : l){
                res[i] = item;
                i++;
            }
        }
        return res;
    }

    private List<Integer> topoSort(Map<Integer, Set<Integer>> itemGraph, 
    Map<Integer, Integer> indegreeItem, int countOfItems) {

        Queue<Integer> q = new LinkedList<>();
        List<Integer> res = new ArrayList<>();

        for(int i: itemGraph.keySet()){
            if(indegreeItem.getOrDefault(i,0)==0)
                q.add(i);
        }

        while(!q.isEmpty()){
            int pop = q.poll();

            countOfItems--;
            res.add(pop);

            for(int nextItem : itemGraph.get(pop)){
                int indegreeOfNextItem = indegreeItem.get(nextItem)-1;
                indegreeItem.put(nextItem, indegreeOfNextItem);
                if(indegreeOfNextItem==0)
                    q.add(nextItem);
            }
        }

        if(countOfItems==0) return res;
        else return new ArrayList<>();

    }
}
maqianxiong commented 2 years ago

657. 机器人能否返回原点 - 力扣(LeetCode) (leetcode-cn.com)

思路

代码

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

     }
}

复杂度分析

dahuang257 commented 2 years ago

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

jaysonss commented 2 years ago

思路

模拟

代码

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

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

    # 0 n 0 1
ZETAVI commented 2 years ago

思路

遍历字符串-模拟小车移动

语言

java

代码

public boolean judgeCircle(String moves) {
        int lr=0,ud=0;
        for (int i = 0; i < moves.length(); i++) {
            switch (moves.charAt(i)){
                case 'L':lr--;break;
                case 'R':lr++;break;
                case 'D':ud--;break;
                case 'U':ud++;break;
                default:
            }
        }
        if (lr==0&&ud==0)return true;
        return false;
    }

复杂度分析

winterdogdog commented 2 years ago
/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function(moves) {
    let sum1 = 0, sum2 = 0;
    moves.split('').forEach(item => {
        switch(item) {
            case 'U':
                sum1++;
                break
            case 'D':
                sum1--;
                break
            case 'L':
                sum2++;
                break
            case 'R':
                sum2--
                break
        }
    })
    return (sum1 === 0 && sum2 === 0) ? true : false
};
wangwiitao commented 2 years ago

思路

模拟在x轴y轴移动,判断最后在出发点

代码

var judgeCircle = function (moves) {
    let x = 0;
    let y = 0;
    for (let i = 0; i < moves.length; i++) {
        if(moves[i]==="L")x--;
        if(moves[i]==="R")x++;
        if(moves[i]==="U")y++;
        if(moves[i]==="D")y--;
    }
    return x == 0 && y ==0;
};
qibao1112 commented 2 years ago

思路

定义x、y参数表示横坐标和纵坐标,遍历字符串的字符,移动坐标(x,y),编辑结束之后,判断坐标是否为(0,0)

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

复杂度

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

shibingchao123 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;

};

CruiseYuGH commented 2 years ago

思路

关键点

代码

Python3 Code:


class Solution:
    def judgeCircle(self, moves: str) -> bool:
        path = {'U': [0,1], 'D': [0,-1], 'L': [-1,0], 'R':[1,0]}
        begin = [0,0]
        for move in moves:
            begin[0] +=path[move][0]
            begin[1] +=path[move][1]
        print(begin)
        if begin ==[0,0]:
            return True
        return False

复杂度分析

令 n 为数组长度。

joriscai commented 2 years ago

思路

代码

javascript

/*
 * @lc app=leetcode.cn id=657 lang=javascript
 *
 * [657] 机器人能否返回原点
 */

// @lc code=start
/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function(moves) {
  let x = 0
  let y = 0
  for (let i = 0; i < moves.length; i++) {
    const move = moves[i];
    if (move === 'U') {
      y++
    }
    if (move === 'D') {
      y--
    }
    if (move === 'R') {
      x++
    }
    if (move === 'L') {
      x--
    }
  }

  return x === 0 && y === 0
};
// @lc code=end

复杂度分析

ff1234-debug commented 2 years ago

思路

模拟法

初始坐标(0,0)遍历字符进行y:上加下减 x:左加右减,判断最终能否 回到(0,0)

代码

实现语言: C++

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

复杂度分析

Venchyluo commented 2 years ago

可以模拟带入上下左右的步数。最后确认有没有回到原点即可。
第二种就更简单了,直接确认上下, 左右出现的次数相同就肯定在原点了

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

Time complexity: O(N)
Space complexity: O(1) 这个dict 存了4个elements 不需要算O(N)吧


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

Time complexity: O(N)
Space complexity: O(N)

flagyk5 commented 2 years ago
'''
时间:n
空间:1
'''

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

657. Robot Return to Origin

Click Me

Algo

  1. Direct Simulation

Code

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = 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

        return x == 0 and y == 0

Comp

T: O(len(moves))

S: O(1)

shanrufu commented 2 years ago
bool judgeCircle(char *moves) {
  int n = strlen(moves), x = 0, y = 0;
  for (int i = 0; i < n; i++) {
    switch (moves[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)

xinhaoyi commented 2 years ago

657. 机器人能否返回原点

在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。

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

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

示例 1:

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

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

思路一

用一个x和y去模拟上下左右,原点是(0,0),它只要经过一番操作还能回到(0,0),就说明可以回到原点

代码

class Solution {
    public boolean judgeCircle(String moves) {
        //用一个x,y去模拟上下左右的过程,原点是(0,0),它只要经过一番操作还能回到(0,0)
        //就说明可以回到原点
        int x = 0;
        int y = 0;
        char[] movesArray = moves.toCharArray();
        for(int i = 0; i < movesArray.length; i ++){
            switch(movesArray[i]){
                case 'U' :
                {
                    y ++;
                    break;
                }
                case 'D' :
                {
                    y --;
                    break;
                }
                case 'R' :
                {
                    x ++;
                    break;
                }
                case 'L' :
                {
                    x --;
                    break;
                }
            }
        }

        if(x == 0 && y == 0){
            return true;
        }
        else{
            return false;
        }

    }
}

复杂度分析

时间复杂度:$O(n)$

空间复杂度:$O(1)$

Zhang6260 commented 2 years ago

JAVA版本

思路:使用二个值来表示当前位置的坐标,然后对moves进行遍历,并对坐标进行相应的修改,最后判断是否能够回到初始的值。

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

时间复杂度:O(n)

空间复杂度:O(1)

moxiaopao278 commented 2 years ago

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