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

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

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.

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

相关推荐
似水এ᭄往昔8 分钟前
【C++】--封装红⿊树实现mymap和myset
开发语言·数据结构·c++·算法·stl
咕噜企业分发小米10 分钟前
腾讯云向量数据库HNSW索引如何更新?
人工智能·算法·腾讯云
charlie11451419113 分钟前
嵌入式现代C++教程:C++98——从C向C++的演化(3)
c语言·开发语言·c++·笔记·学习·嵌入式
lcreek15 分钟前
LeetCode215. 数组中的第K个最大元素、LeetCode912. 排序数组
python·算法·leetcode
moonquakeTT18 分钟前
C++:深拷贝与浅拷贝
c++
程序员zgh20 分钟前
C语言 指针用法与区别(指针常量、常量指针、指针函数、函数指针、二级指针)
c语言·开发语言·jvm·c++
Einsail29 分钟前
天梯赛题解(3-6)
算法
杜子不疼.30 分钟前
【LeetCode 852 & 162_二分查找】山脉数组的峰顶索引 & 寻找峰值元素
算法·leetcode·职场和发展
山楂树の33 分钟前
搜索插入位置(二分查找)
数据结构·算法
冉佳驹36 分钟前
C++ ——— 仿函数的使用、继承方式、赋值转换规则、菱形继承与虚继承
c++·继承·virtual·仿函数·菱形继承·模板特化·虚继承