机器人能否回到原点 - 简单

*************

C++

topic:657. 机器人能否返回原点 - 力扣(LeetCode)

*************

inspect the topic very first.

|----------------------------------------------------------------------------|
| |

It is letters to decide which side the robot moves. And my thought is quite sample. Assumeing the robot can move back to the origin, then the numbers of L have to be the same with the numbers of R. So are U and D.

Then the code can be easy to write. Travel through the string and count the letters.

cpp 复制代码
class Solution {
public:
    bool judgeCircle(string moves) {
        
        int n = moves.size(); // to figure out the size at first
        int countR = 0;
        int countL = 0;
        int countU = 0;
        int countD = 0;

        for (int i = 0; i < n; i++)
        {
            if (moves[i] == 'R')
            {
                countR = countR + 1;
            }
            else if (moves[i] == 'L')
            {
                countL = countL + 1;
            }
            else if (moves[i] == 'U')
            {
                countU = countU + 1;
            }
            else
            {
                countD++;
            }
        }

        if (countR == countL && countD == countU)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

|----------------------------------------------------------------------------|
| |

However, I donot think it is a elegent code. If you gays finish the Nine-year compulsory education,you will know coordinate system.

|-----------------------------------------------------------------------------|
| |

↑ y = y + 1;

↓ y = y - 1;

← x = x - 1;

→ x = x + 1;

cpp 复制代码
class Solution {
public:
    bool judgeCircle(string moves) {
        int x = 0;
        int y = 0;

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

|----------------------------------------------------------------------------|
| |

It is do elegent.

Maybe apple would change the design of ios in the near future. I donot care whether the ios system is fluently or not, I just want to see what desigh looks.

|----------------------------------------------------------------------------|
| |

相关推荐
椰子今天很可爱13 分钟前
仿照muduo库实现一个高并发服务器
linux·服务器·c++
alphaTao1 小时前
LeetCode 每日一题 2025/12/15-2025/12/21
算法·leetcode
写写闲篇儿4 小时前
下一个更大元素(一)
数据结构·算法
MobotStone5 小时前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
lizz316 小时前
C++模板编程:从入门到精通
java·开发语言·c++
炽烈小老头6 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
Queenie_Charlie7 小时前
HASH表
数据结构·c++·哈希算法
Xの哲學7 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
soft20015257 小时前
MySQL Buffer Pool深度解析:LRU算法的完美与缺陷
数据库·mysql·算法
superman超哥7 小时前
仓颉语言中锁的实现机制深度剖析与并发实践
c语言·开发语言·c++·python·仓颉