C++ easy and short solution


  • 0
    M
        bool judgeCircle(string moves) {
            int x=0, y=0;
            for(int i=0;i<moves.size();i++) {
                switch(moves[i]) {
                    case 'U': x--; break;
                    case 'D': x++; break;
                    case 'L': y--; break;
                    case 'R': y++; break;
                }
            }
            return x==0&&y==0;
        }

  • 0
    B

    I get time exceeded for this...whats wrong? (54/62 only pass)

    bool judgeCircle(char* moves) {
        int i=0, x=0, y=0;
        for(;i<strlen(moves);i++){
            switch(moves[i]){
                case 'L': x-=1;break;
                case 'R': x+=1;break;
                case 'U': y+=1;break;
                case 'D': y-=1;break;
            }
        }
        if(x==0 && y==0) return true;
        return false;
    }
    

  • 0

    Hi @b_s, your code will get accepted by the OJ if you move the strlen() function call outside of the for-loop ( please see this modification below ). I believe you are receiving TLE because strlen() is an O(N) function which is invoked at runtime for every iteration of the for-loop. strlen() iterates from the beginning of the string until it reaches the NULL char \0 in order to calculate the string length. The TC which caused TLE contains 20,000 characters. So strlen() ends up traversing these 20,000 chars 20,000 times (once for each loop iteration). This ends up being 400,000,000 chars and causes TLE.

        bool judgeCircle(char* moves) {
            int i=0, x=0, y=0;
            int length = strlen(moves);
            for(;i<length;i++){
                switch(moves[i]){
                    case 'L': x-=1;break;
                    case 'R': x+=1;break;
                    case 'U': y+=1;break;
                    case 'D': y-=1;break;
                }
            }
            if(x==0 && y==0) return true;
            return false;
        }
    

Log in to reply
 

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