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的個數也得相等。這不就是之前那道Valid Parentheses的變種么,這次博主終於舉一反三了!這比括號那題還要簡單,因為括號至少還有三種,這里就水平和豎直兩種。比較簡單的方法就是使用兩個計數器,如果是U,則cnt1自增1;如果是D,cnt1自減1。同理,如果是L,則cnt1自增1;如果是R,cnt1自減1。最后只要看cnt1和cnt2是否同時為0即可,參見代碼如下:
解法一:
class Solution { public: bool judgeCircle(string moves) { int cnt1 = 0, cnt2 = 0; for (char move : moves) { if (move == 'U') ++cnt1; else if (move == 'D') --cnt1; else if (move == 'L') ++cnt2; else if (move == 'R') --cnt2; } return cnt1 == 0 && cnt2 == 0; } };
下面這種解法使用了哈希表來建立字符和其出現的次數之間的映射,最后直接比較對應的字符出現的次數是否相等即可,參見代碼如下:
解法二:
class Solution { public: bool judgeCircle(string moves) { unordered_map<char, int> m; for (char c : moves) ++m[c]; return m['L'] == m['R'] && m['U'] == m['D']; } };
類似題目:
參考資料:
https://discuss.leetcode.com/topic/99256/c-counter-4-lines-solution