C++ Solution Using Dictionary

  • 0

    A robot ends up in the same place when the number of 'up' steps equal the number of 'down' steps and the number of 'left' steps equals the number of 'right' steps. There are a couple of cases that can be evaluated trivially: when the input string is empty, there is no movement, and therefore the output should be true, and when the input string has an odd number of entries the output should be false. Next, I built a dictionary with char key: {'U','D','L','R'} and value corresponding to the number of occurrences of the key in the input string. The whole solution is:

    class Solution {
        bool judgeCircle(string moves) {
            if (moves.size()==0) return true;
            if (moves.size() % 2 == 1) return false;
            std::map<char,size_t> counts; 
            counts['U'] = std::count(moves.begin(),moves.end(),'U');
            counts['D'] = std::count(moves.begin(),moves.end(),'D');
            counts['L'] = std::count(moves.begin(),moves.end(),'L');
            counts['R'] = std::count(moves.begin(),moves.end(),'R');
            return ( (counts['U'] == counts['D']) && (counts['L'] == counts['R']) );

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.