1472. Design Browser History

LeetCode medium original: C# #csharp #design #leetcode #medium #stack #string
選択した UI 言語に合わせて問題文をロシア語から翻訳します。コードは変更しません。

У вас есть браузер с одной вкладкой, где вы начинаете на домашней странице и можете посетить другой URL, вернуться назад на определённое количество шагов в истории или переместиться вперёд на определённое количество шагов в истории.

Реализуйте класс BrowserHistory:

BrowserHistory(string homepage) Инициализирует объект с домашней страницей браузера.

void visit(string url) Посещает URL с текущей страницы. Это очищает всю историю вперёд.

string back(int steps) Перемещает на steps шагов назад в истории. Если вы можете вернуться только на x шагов в истории, а steps > x, вы вернётесь только на x шагов. returns текущий URL после перемещения назад в истории на не более чем steps шагов.

string forward(int steps) Перемещает на steps шагов вперёд в истории. Если вы можете переместиться только на x шагов вперёд в истории, а steps > x, вы переместитесь только на x шагов. returns текущий URL после перемещения вперёд в истории на не более чем steps шагов.

例:

Input:

["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]

[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]

Output:

[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]

Explanation:

BrowserHistory browserHistory = new BrowserHistory("leetcode.com");

browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"

browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"

browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"

browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"

browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"

browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"

browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"

browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.

C# 解法

照合済み/オリジナル
using System.Collections.Generic;
public class BrowserHistory {
    private Stack<string> history;
    private Stack<string> future;
    private string current;
    public BrowserHistory(string homepage) {
        history = new Stack<string>();
        future = new Stack<string>();
        current = homepage;
    }
    
    public void Visit(string url) {
        history.Push(current);
        current = url;
        future.Clear();
    }
    
    public string Back(int steps) {
        while (steps > 0 && history.Count > 0) {
            future.Push(current);
            current = history.Pop();
            steps--;
        }
        return current;
    }
    
    public string Forward(int steps) {
        while (steps > 0 && future.Count > 0) {
            history.Push(current);
            current = future.Pop();
            steps--;
        }
        return current;
    }
}

C++ 解法

自動ドラフト、提出前に確認
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class BrowserHistory {
    private stack<string> history;
    private stack<string> future;
    private string current;
    public BrowserHistory(string homepage) {
        history = new stack<string>();
        future = new stack<string>();
        current = homepage;
    }
    
    public void Visit(string url) {
        history.push(current);
        current = url;
        future.Clear();
    }
    
    public string Back(int steps) {
        while (steps > 0 && history.size() > 0) {
            future.push(current);
            current = history.pop();
            steps--;
        }
        return current;
    }
    
    public string Forward(int steps) {
        while (steps > 0 && future.size() > 0) {
            history.push(current);
            current = future.pop();
            steps--;
        }
        return current;
    }
}

Java 解法

照合済み/オリジナル
class BrowserHistory {
    private Stack<String> history, future;
    private String current;
    
    public BrowserHistory(String homepage) {
        history = new Stack<String>();
        future = new Stack<String>();
        current = homepage;
    }
    
    public void visit(String url) {
        history.push(current);
        current = url;
        future = new Stack<String>();
    }
    
    public String back(int steps) {
        while(steps > 0 && !history.empty()) {
            future.push(current);
            current = history.pop();
            steps--;
        }
        return current;
    }
    
    public String forward(int steps) 
        while(steps > 0 && !future.empty()) {
            history.push(current);
            current = future.pop();
            steps--;
        }
        return current;
    }
}

JavaScript 解法

照合済み/オリジナル
class BrowserHistory {
    constructor(homepage) {
        this.history = [];
        this.future = [];
        this.current = homepage;
    }

    visit(url) {
        this.history.push(this.current);
        this.current = url;
        this.future = [];
    }

    back(steps) {
        while (steps > 0 && this.history.length > 0) {
            this.future.push(this.current);
            this.current = this.history.pop();
            steps--;
        }
        return this.current;
    }

    forward(steps) {
        while (steps > 0 && this.future.length > 0) {
            this.history.push(this.current);
            this.current = this.future.pop();
            steps--;
        }
        return this.current;
    }
}

Go 解法

照合済み/オリジナル
package main

type BrowserHistory struct {
    history []string
    future  []string
    current string
}

func Constructor(homepage string) BrowserHistory {
    return BrowserHistory{
        current: homepage,
    }
}

func (this *BrowserHistory) Visit(url string) {
    this.history = append(this.history, this.current)
    this.current = url
    this.future = []string{}
}

func (this *BrowserHistory) Back(steps int) string {
    for steps > 0 && len(this.history) > 0 {
        this.future = append(this.future, this.current)
        this.current = this.history[len(this.history)-1]
        this.history = this.history[:len(this.history)-1]
        steps--
    }
    return this.current
}

func (this *BrowserHistory) Forward(steps int) string {
    for steps > 0 && len(this.future) > 0 {
        this.history = append(this.history, this.current)
        this.current = this.future[len(this.future)-1]
        this.future = this.future[:len(this.future)-1]
        steps--
    }
    return this.current
}

Algorithm

1⃣Инициализация:

Создайте класс BrowserHistory с двумя стеками (history и future) и строковой переменной current для хранения текущего URL. Инициализируйте current с домашней страницей.

2⃣Посещение URL:

Метод visit(url) сохраняет текущий URL в стеке history, устанавливает url как текущий и очищает стек future.

3⃣Навигация назад и вперед:

Метод back(steps) перемещает текущий URL в стек future и извлекает URL из стека history, пока шаги не будут исчерпаны или стек history не станет пустым.

Метод forward(steps) перемещает текущий URL в стек history и извлекает URL из стека future, пока шаги не будут исчерпаны или стек future не станет пустым.

😎

Vacancies for this task

有効な求人 with overlapping task tags are 表示.

すべての求人
有効な求人はまだありません。