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

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

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.

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

相关推荐
风筝在晴天搁浅4 分钟前
代码随想录 300.最长递增子序列
算法·动态规划
小O的算法实验室5 分钟前
2026年EAAI SCI1区TOP,基于进化算法的多目标施工现场布局与安全规划模型,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
尋有緣6 分钟前
力扣1083-销售分析II
leetcode·oracle·数据库开发
.小小陈.6 分钟前
C++初阶5:string类使用攻略
开发语言·c++·学习·算法
代码游侠11 分钟前
数据结构——树
数据结构·算法
天骄t12 分钟前
树与哈希:数据结构核心解析
数据结构·算法
神奇的代码在哪里13 分钟前
C++的演进与我的编程学习之旅:从底层基础到AI应用
c++·人工智能·python·学习·程序人生·个人开发
小年糕是糕手16 分钟前
【C++】类和对象(六) -- 友元、内部类、匿名对象、对象拷贝时的编译器优化
开发语言·c++·算法·pdf·github·排序算法
ShineLeong16 分钟前
C的第一次
数据结构·算法
大佬,救命!!!19 分钟前
C++本地配置OpenCV
开发语言·c++·opencv·学习笔记·环境配置