[C++] 94% O(n) time & O(1) space


  • 0
    X

    'D' = 68 , 'L' = 76 , 'R' = 82 and 'U' = 85 in int
    Produce an array which can fit 18 elements(85-68+1) and make Increments at this 4 letters(turn into integer) in array.
    If amount of 'D'(68-68) in array is the same as amount of 'U'(85-85) and so do 'L' & 'R' , the robot back to same place.
    If not, we return a false;

    class Solution {
    public:
        bool judgeCircle(string moves) {
            int movesInt[18] = {0};
            string::iterator iter = moves.begin();
    
            while(iter != moves.end())
            {
                movesInt[*iter - 68]++;
                iter++;
            }
            return (movesInt[0]==movesInt[17]) && (movesInt[8]==movesInt[14]) ;
        }
    };
    

Log in to reply
 

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