657. Judge Route Circle(sync_with_stdio)加速

本文介绍了LeetCode上第657题Judge Route Circle的解题思路及代码实现,探讨了如何判断机器人是否回到起点,并分享了提高代码运行效率的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一次用 优快云 写博客哈,想把自己刷 leetcode 的所思所想所获得的东西写在一个地方,那就简单粗暴一点,用 优快云 吧。

657. Judge Route Circle

leetcode 的第 657 题

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
Example 1:
Input: “UD”
Output: true
Example 2:
Input: “LL”
Output: false

是很简单的题目,但是把代码提交后发现速度不是很快,有好多大佬速度很快,在6ms完成,而我居然要30来ms。


class Solution {
public:
    bool judgeCircle(string moves) {
        int L = 0, U = 0;
        for (int i = 0; i < moves.length(); i++)
        {
            if (moves[i] == 'L')
                L++;
            else if (moves[i] == 'R')
                L--;
            else if (moves[i] == 'U')
                U++;
            else if (moves[i] == 'D')
                U--;
        }
        if (L == 0 && U == 0)
            return true;
        else
            return false;
    }
};

加了一段优化后

static string moves =[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return "";
}();

class Solution {
public:
    bool judgeCircle(string moves) {
        int L = 0, U = 0;
        for (int i = 0; i < moves.length(); i++)
        {
            if (moves[i] == 'L')
                L++;
            else if (moves[i] == 'R')
                L--;
            else if (moves[i] == 'U')
                U++;
            else if (moves[i] == 'D')
                U--;
        }
        if (L == 0 && U == 0)
            return true;
        else
            return false;
    }
};
std::ios::sync_with_stdio(false);
cin.tie(NULL);

之前写的题目是用 cout 和 cin ,会 Timeout,如果用 printf 和 scanf 的话就能完成 AC 。之前只觉得cout cin 慢,原来是可以用这玩意加速的呀。

记住!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值