Open azl397985856 opened 2 years ago
定义一个初始坐标(x, y), 每次从moves数组读入一个字符, 根据具体反向进行一次x或y的增减。 看循环结束时, 是否能使 x == 0 且 y ==0 。
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;
}
};
设置x y坐标,模拟即可
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
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)
https://leetcode.com/problems/robot-return-to-origin/
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)
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 为数组长度。
计算水平和竖直方向的move,往左就水平+1,往右水平-1,往上竖直+1,往下竖直-1
最后判断这两个是不是0
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
Time O(n)
Space O(1)
模拟。最后看返回的坐标是否为(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;
}
}
复杂度分析
入门的模拟题,模拟水平和垂直坐标系,机器人向对应方向移动时,对应的坐标值加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)
由于这里只有两个维度,于是用复数来表示移动比较方便。按照方向移动后,判断最后是否为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)
思路:按照题目的意思模拟
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)
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;
}
}
}
按照题目来模拟
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: O(n) space: O(1) no extra spaces needed
Stimulate the moves according to the instruction. Then check whether the end is [0, 0]
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]
Time: O(n). n is the length of the instruction Space: O(1)
# 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
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)
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;
};
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;
};
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
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)
Problem Link
Ideas
Complexity: hash table and bucket
Code
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']
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;
}
}
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
思路:没啥思路,
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), 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
simulation
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;
}
}
Time = O(N): iterate over the whole string
Space = O(1)
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依旧是常数级
简单题,给个变量表示坐标,各个方向对应加减即可
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))
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)
}
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)
python
class Solution:
def judgeCircle(self, moves: str) -> bool:
d = {'R': (1, 0), 'L': (-1, 0), 'U': (0, 1), 'D': (0, -1)}
dx, dy = 0, 0
for m in moves:
dx += d[m][0]
dy += d[m][1]
return dx == 0 and dy == 0
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)
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)
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)
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)
思路:
方法一、模拟法, 是否回到原点与起始位置无关,只与移动的路径有关(string moves),使用两个v, l变量存放水平和垂直的移动,每次一步
复杂度分析:
代码(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;
}
};
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
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;
}
};
直接模拟四个方向,最后判断坐标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)
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; } }
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)
/**
* @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)
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);
}
};
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 为数组长度。
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)
遍历进行运算
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 为数组长度。
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;
}
}
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;
}
}
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;
}
}
变量表示坐标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;
}
}
用两个变量分别表示水平坐标和垂直坐标 判断移动后位置是否在原点
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;
}
};
复杂度分析
思路: 一开始本能用哈希表,后面发现空间复杂度太多了。 一开始用四个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)
哈希表记录方向 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)
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,因为它在移动结束时没有返回原点。