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

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

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.

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

相关推荐
Java版蜡笔小新几秒前
算法-贪心算法
算法·贪心算法
LuckyAnJo9 分钟前
Leetcode-100 回溯法-电话号码的字母组合
python·算法·leetcode
HR Zhou17 分钟前
群体智能优化算法-鹈鹕优化算法(Pelican Optimization Algorithm, POA,含Matlab源代码)
算法·机器学习·matlab·优化·群体智能优化
钰爱&22 分钟前
【Qt】ffmpeg编码—存储(H264)
c++·qt·ffmpeg
LuckyLay28 分钟前
LeetCode算法题(Go语言实现)_20
算法·leetcode·职场和发展·golang
想要成为计算机高手42 分钟前
12. STL的原理
开发语言·c++·经验分享·stl
Heisenberg~1 小时前
C++ 多态:面向对象编程的核心概念(二)
c++
Phoebe鑫1 小时前
数据结构每日一题day7(顺序表)★★★★★
算法
Suc_zhan3 小时前
实验二 如何将随机森林算法应用于激酶抑制剂分类任务
python·算法·随机森林·机器学习
小学仔3 小时前
leetcode -编辑距离
java·算法·动态规划