Scala Solution


  • 0
    L

    O(n) time

    we declare a horizontal and vertical position variables (h,v)
    we iterate over the string and of each change in each axis we add or subtract the value of the position in that axis.

    assuming we start in (0,0) we will check if horizontal and vertical positions are equal and one of the is equal to zero

    def judgeCircle(moves: String): Boolean = {
      var h = 0
      var v = 0
      moves.foreach {
        case 'U' => v = v + 1
        case 'D' => v = v - 1
        case 'L' => h = h + 1
        case 'R' => h = h - 1
      }
    
      h == v && h == 0
    }
    

Log in to reply
 

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