[Oracle] LeetCode 1472 Design Browser History 双stack
You have a browser of one tab where you start on the homepage
and you can visit another url
, get back in the history number of steps
or move forward in the history number of steps.
Implement the BrowserHistory class:
BrowserHistory(string homepage)
Initializes the object with the homepage of the browser.void visit(string url)
Visits url from the current page. It clears up all the forward history.string back(int steps)
Move steps back in history. If you can only return x steps in the history andsteps > x
, you will return only x steps. Return the current url after moving back in history at most steps.string forward(int steps)
Move steps forward in history. If you can only forward x steps in the history andsteps > x
, you will forward only x steps. Return the current url after forwarding in history at most steps.
Solution
我们用两个 \(stack\) 分别来存储 \(history, feature\) 的网页,每次 \(back\) 的时候将网页网页 \(push\) 到 \(feat\) 里面,每次 \(forward\) 的时候,则 \(push\) 到 \(his\)
点击查看代码
class BrowserHistory {
private:
stack<string> his;
stack<string> feat;
public:
BrowserHistory(string homepage) {
his.push(homepage);
feat = stack<string> ();
}
void visit(string url) {
his.push(url);feat = stack<string> ();
}
string back(int steps) {
while(steps>0 && his.size()>1){
feat.push(his.top());
his.pop();
steps--;
}
return his.top();
}
string forward(int steps) {
while(steps>0 && feat.size()>0){
his.push(feat.top());
feat.pop();
steps--;
}
return his.top();
}
};
/**
* Your BrowserHistory object will be instantiated and called as such:
* BrowserHistory* obj = new BrowserHistory(homepage);
* obj->visit(url);
* string param_2 = obj->back(steps);
* string param_3 = obj->forward(steps);
*/