Daily LeetCode Challenge - 1472. Design Browser History

Min Young Kim·2023년 3월 18일
0

algorithm

목록 보기
96/198

Problem From.
https://leetcode.com/problems/design-browser-history/

오늘 문제는 인터넷 방문, 뒤로가기, 앞으로 가기 함수를 직접 구현하는 문제였다.
방문, 뒤로, 앞으로가 들어있는 리스트와 방문한 페이지가 들어있는 리스트가 주어진다고 가정하고 방문과 뒤로가기 앞으로 가기를 각각 구현해야했는데, 뒤로가기 스택과 앞으로 가기 스택을 만들어두고, 각각의 동작마다 행동을 정의해주었다.

import java.util.*

class BrowserHistory(homepage: String) {

    var current = homepage
    val backHistory = Stack<String>()
    val forwardHistory = Stack<String>()
    
    fun visit(url: String) {
        backHistory.push(current)
        forwardHistory.clear()
        current = url
    }

    fun back(steps: Int): String {
        if(backHistory.isEmpty()) return current
        forwardHistory.push(current)
        for(i in 1 until minOf(steps, backHistory.size)) {
            forwardHistory.push(backHistory.pop())
        }
        current = backHistory.pop()
        return current
    }

    fun forward(steps: Int): String {
        if(forwardHistory.isEmpty()) return current
        backHistory.push(current)
        for(i in 1 until minOf(steps, forwardHistory.size)) {
            backHistory.push(forwardHistory.pop())
        }
        current = forwardHistory.pop()
        return current
    }

}
profile
길을 찾는 개발자

0개의 댓글