657. Judge Route Circle

题目描述:

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

解题思路:
统计输入字符串中字符U和D的个数是否一样,L和R个数是否一样,若都一样,则返回到起点。

代码:
 1 class Solution {
 2 public:
 3     bool judgeCircle(string moves) {
 4         
 5         int u = 0;
 6         int d = 0;
 7         int l = 0;
 8         int r = 0;
 9         u = std::count(moves.begin(), moves.end(), 'U');
10         d = std::count(moves.begin(), moves.end(), 'D');
11         l = std::count(moves.begin(), moves.end(), 'L');
12         r = std::count(moves.begin(), moves.end(), 'R');
13         return (u == d) && (l == r);   
14     }
15 };

 

posted @ 2018-07-29 15:38  gszzsg  阅读(118)  评论(0编辑  收藏  举报