657. Judge Route Circle

Description

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

Solution

简单题。

class Solution {
    public boolean judgeCircle(String moves) {
        int xOffset = 0;
        int yOffset = 0;
        
        for (int i = 0; i < moves.length(); ++i) {
            switch(moves.charAt(i)) {
                case 'R':
                    ++xOffset;
                    continue;
                case 'L':
                    --xOffset;
                    continue;
                case 'U':
                    ++yOffset;
                    continue;
                case 'D':
                    --yOffset;
                    continue;
                default:
                    continue;
            }
        }
        
        return xOffset == 0 && yOffset == 0;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 时光的白鸟踅摸迂回 驻足在下一片沼泽地 他们甘之如饴 越陷越深 那些文字 其中的奥秘 是童话 是寓言 蝌蚪可以吞...
    蔷薇花的记忆阅读 667评论 9 7
  • 《蜗牛慢吞吞》是我买了有一阵的书,因为网上介绍说它被评为2012年度“中国最美的书”才引起我的购买欲望,想一探究竟...
    一江春水1990阅读 445评论 0 3
  • 昨晚,妈妈在电话中哭诉,刚买的手机丢了,心里难受。她开始否认自己存在的价值了,表示自己过活了大半辈子,没做过什么有...
    一只迷路的麋鹿阅读 439评论 0 0
  • 文/蜀山倦客 忆腊梅初绽琼花落。征轮去、驰目长亭,身影渐销山廓。回头返室,壁上清灯照离索。欹几坐、沉醉杯觞,此...
    寺咀山主人阅读 293评论 2 15