Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] AC #208

Closed
hwangJi-dev opened this issue Apr 20, 2023 · 0 comments
Closed

[Algorithm] AC #208

hwangJi-dev opened this issue Apr 20, 2023 · 0 comments
Assignees

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Apr 20, 2023

💬 문제

https://www.acmicpc.net/problem/5430


💬 Idea

  • 함수 수행시 R이 나올 때마다 reverse를 수행하고, D가 나올 때마다 removeFirst()를 수행해주었더니 시간 초과가 발생했다.
  • 따라서 투포인터 방식을 활용해서 풀이해주었다.
    • R을 수행할 차례라면 isReverse flag를 변경해준다
    • D를 수행할 차례라면
      1. pointer가 reversepointer보다 크다면 → error인 경우이므로 error를 출력하고 continue문을 수행시킨다. (labeled로 인해 중첩 for문 같이 영향)
      2. isReversed flag 상태라면 → reversepointer를 좁혀준다.
      3. isReversed flag 상태가 아니라면 → pointer 범위를 늘려준다.
    • RD 함수 종료 후
      • pointer가 reversepointer보다 크다면 빈 배열을 의미하므로 []를 출력한다.
      • 그렇지 않다면 pointer부터 reversepointer까지 배열을 slice한 후 출력 조건에 맞게 배열을 맵핑한 뒤 출력한다.
        • (배열 자체를 출력할 경우 [1,2,3] 과 같이 출력되지 않고 [1, 2, 3] 과 같이 출력되므로 답이 틀리다고 나오므로 주의하자.)

💬 풀이

import Foundation

func solution5430() {
    let t = Int(readLine()!)!
    
outloop: for _ in 0..<t {
        let function = readLine()!
        let n = Int(readLine()!)!
        let arr = readLine()!.trimmingCharacters(in: ["[", "]"]).split(separator: ",").map({ Int(String($0))! })
        var pointer = 0
        var reversepointer = n - 1
        var isReverse = false
    
        for i in function {
            if i == "R" {
                isReverse = !isReverse
            } else {
                if pointer > reversepointer {
                    print("error")
                    continue outloop
                }
                
                if isReverse {
                    reversepointer -= 1
                } else {
                    pointer += 1
                }
            }
        }
        
        if pointer > reversepointer {
            print("[]")
        } else {
            var ans = arr[pointer...reversepointer]
            if isReverse {
                ans.reverse()
            }
            print("[" + ans.map({ String($0) }).joined(separator: ",") + "]")
        }
    }
}

💬 알게된 문법

  • for문에 레이블을 붙여 사용하면 중첩 for문도 한꺼번에 탈출이 가능하다.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant