Easy 2 lines Java


  • 4
    T

    Easy solution using split.(It needs spaces from front and behind to be calculated correctly):

     public boolean judgeCircle(String moves) {
            moves=" " + moves + " ";
            return moves.split("L").length==moves.split("R").length && moves.split("U").length == moves.split("D").length;
        }
    

  • 1
    J

    @Toaster

    Why do we need spaces before and after the string.It will work without them also right


  • 0
    T

    @jogiraju
    It's not working without spaces you can try it simply without, it wouldn't work for cases like "UD".I agree that it's a little bit confusing,but this is because if we "UD".split("U") then we will get an array of 2 elements "" and "D", if we split by "D" then we will get "U" , so in the second case there will be only one element in the array.I recommend you to simply try it using this simple code

    System.out.println("UD".split("U")[0]); //the result will be empty ""
     System.out.println("UD".split("U")[1]); //the result will be D
    System.out.println("UD".split("D")[0]); //the result will be U
    System.out.println("UD".split("D")[1]); //the result will be ArrayIndexOutOfBoundsException
    

    This is because when after split "" empty is the last elements,then it isn't added to the array,so to solve it we simply add spaces.
    Hope it makes clearer


  • 1
    R

    If that's the case, I think you just need to add space at the end of moves.
    moves= moves + " ";


  • 0
    T

    @ruikiwi Oh, nice that should be working also!Thanks for advice


  • 0
    Y

    @jogiraju Not really. For example "UDUDLRLR" after split is
    --D--DLRLR--
    U--U--LRLR--
    UDUD--R--R--
    UDUDL--L--
    that means if we split the letter is the last letter, it will lose 1 string.


  • 0
    C

    @Toaster Instead of adding whitespaces, you can use moves.split("U",-1). Adding -1 applies the split function as many times possible on the pattern. Although I would recommend not using split() in interviews.


  • 1
    R

    This is not a good solution as split commands will result in traversing the same string 4 times, while you only need to traverse the string just once in order to find out the result.


  • 0
    I

    @rahiminasab.e agreed. And creating a new string on each recursive call is more expensive.

    It's an interesting solution though.


Log in to reply
 

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