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

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

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.

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

相关推荐
weixin_30777913几秒前
ClickHouse Windows迁移方案与测试
linux·c++·数据仓库·windows·clickhouse
大阳1232 分钟前
数据结构(概念及链表)
c语言·开发语言·数据结构·经验分享·笔记·算法·链表
老猿讲编程11 分钟前
LCM中间件入门(1):工作原理核心概念及Ubuntu环境下的C++实践
c++·ubuntu·中间件·lcm
2501_9247319931 分钟前
驾驶场景玩手机识别:陌讯行为特征融合算法误检率↓76% 实战解析
开发语言·人工智能·算法·目标检测·智能手机
爱掉发的小李1 小时前
Linux 环境下 Docker 安装与简单使用指南
java·linux·运维·c++·python·docker·php
爱编程的鱼1 小时前
计算机(电脑)是什么?零基础硬件软件详解
java·开发语言·算法·c#·电脑·集合
澄澈i1 小时前
设计模式学习[17]---组合模式
c++·学习·设计模式·组合模式
洛生&2 小时前
【abc417】E - A Path in A Dictionary
算法
亮亮爱刷题2 小时前
算法提升之数学(快速幂+逆元求法)
算法
恣艺2 小时前
LeetCode 124:二叉树中的最大路径和
算法·leetcode·职场和发展