Design Browser History
设计一个浏览器的历史记录.
这题我用的是vector, 因为我看到题目要求的visit方法需要把某一点后边所有的历史记录全删除, 所以用cur记录当前访问的位置, 然后用resize()删除[cur+1, v.size() – 1]的范围.
class BrowserHistory {
public:
vector<string> v;
int cur = 0;
BrowserHistory(string homepage) {
v.push_back(homepage);
}
void visit(string url) {
if(cur != v.size() - 1){
v.resize(cur + 1); // remove [cur+1, v.size() - 1]
v.shrink_to_fit();
}
v.push_back(url);
cur++;
}
string back(int steps) {
cur = max(cur - steps, 0);
return v[cur];
}
string forward(int steps) {
cur = min(cur + steps, (int)v.size() - 1);
return v[cur];
}
};
/**
* 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);
*/