Easy 2 lines Java

  • 5

    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


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

  • 1

    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

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

  • 0

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

  • 0

    @jogiraju Not really. For example "UDUDLRLR" after split is
    that means if we split the letter is the last letter, it will lose 1 string.

  • 0

    @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.

  • 2

    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

    @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.