https://leetcode.com/problems/robot-return-to-origin/

 

Robot Return to Origin - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제를 풀이하면 이렇다!

 

시작 점이랑 도착 점이랑 같으면 된다.!!

 

그리고, 움직임들이 주어짐!!

 

그렇다면, 생각을 해볼까요?

 

UP, DOWN, RIGHT, LEFT 가 주어지는데, 

Up은 y+1 

Down은 y-1

Right는 x+1

Left는 x-1

이라고 해석이 가능해지고

 

Switch 문으로 해결해보자!!

 

forEach라는 고차원 함수를 사용했다. 그런다음에 return 에서 (0,0) 이라면 참을 반환해라 로 마무리를 했습니다.

class Solution {
    func judgeCircle(_ moves: String) -> Bool {
        
        var x = 0
        var y = 0

    
        moves.forEach{ move in 
            switch move{
                case "R": x += 1
                case "L": x -= 1
                case "U": y += 1
                case "D": y -= 1     
                default: break
            }
            
        }
        
        return x == 0 && y == 0
    }
}

 

다른 고수분들의 답안을 봐보자.

Hashhhhhh 좋다.

Switch 문보다 이런 Hash도 좋다.

subzTrop
class Solution {
    func judgeCircle(_ moves: String) -> Bool {
        var moves = Array(moves)
        var mapping: [Character: Int] = ["U": 1, "D": -1, "L": -1, "R": 1]
        
        var udtotal = 0
        var lrtotal = 0

        
        for move in moves {
            if move == "U" || move == "D" {
                udtotal += mapping[move]!
            } else {
                lrtotal += mapping[move]!
            }
        }
        
        return udtotal == 0 && lrtotal == 0
    }
}

 

이것도 괜찮은 것 같아서 가져왔다. 하나의 Hash 보다는 하나하나 나누어서 정의 내리고 해결하는 것도 굿.

 

iCodeForExcellence
class Solution {
    func judgeCircle(_ moves: String) -> Bool {
        if (moves.isEmpty) {return true}
        var left = 0
        var right = 0
        var up = 0
        var down = 0
        var result = Array(moves)
        for i in result {
            if(i == "U") {up += 1}
            if(i == "D") {down += 1}
            if(i == "L") {left += 1}
            if(i == "R") {right += 1}
        }
        return ((left - right == 0) && (up - down == 0))
    }
    
}

'Algorithm > Leetcode' 카테고리의 다른 글

Leecode_Flipping an Image  (0) 2022.06.30
Leetcode_Baseball Game  (0) 2022.06.30
Leetcode_fizz-buzz  (0) 2022.06.30
Leetcode_Add digits  (0) 2022.06.30
Leetcode_Add Strings  (0) 2022.06.30

+ Recent posts