Monday, April 7, 2025

735. Asteroid Collision ----M

 We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

 

Example 1:

Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.

Example 2:

Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.

Example 3:

Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.

 

Constraints:

  • 2 <= asteroids.length <= 104
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

A:

理解错误。 

(positive meaning right, negative meaning left).  那么,如果是一个往西,一个往东走, 是碰不到的。

就是左右走着看。  注意,最新加入的,需要跟之前的最后一个比较。 比较完毕,如果有变化,还需要跟再前的比较。

class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> res;
for (auto a : asteroids) {
res.push_back(a);
bool changed = true;
while (changed && res.size() > 1) {
changed = false;
auto a = res.back();
auto b = res[res.size() - 2];
if (b >= 0 && a <= 0) {
changed = true;
res.pop_back();
if (a + b == 0) {
res.pop_back();
} else {
res.back() = abs(b) > abs(a) ? b : a;
}
}
}
}
return res;
}
};







1209. Remove All Adjacent Duplicates in String II ----Medium

You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

 

Example 1:

Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.

Example 2:

Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: 
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"

Example 3:

Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"

 

Constraints:

  • 1 <= s.length <= 105
  • 2 <= k <= 104
  • s only contains lowercase English letters.

 

A:

就是自己弄了个linkded list, 然后一个个加上然后再删除的

(好处是方便最好一个增加或者删除) --------只是beat了 38%

class Solution {
public:
string removeDuplicates(string s, int k) {
int n = s.size();
Node header('@');
Node * tail = &header;
for(char ch : s){
if(ch == tail->ch){
tail->count ++;
if(tail->count == k){
tail = tail->pre;
delete tail->next;
tail->next = nullptr;
}
}else{
Node* node = new Node(ch);
node->pre = tail;
tail->next = node;
tail = tail->next;
}
}
string res;
auto runner = header.next;
while(runner){
string ss(runner->count, runner->ch);
header.next = runner->next;
delete runner;
runner = header.next;
res += ss;
}
return res;
}
private:
struct Node{
char ch;
int count;
Node* pre;
Node* next;
Node(char ch2) : ch(ch2), count(1), pre(nullptr), next(nullptr) {}
};
};




-----------------第二遍----------- 只是用了个vector, 因为根据上面的linkedlist, 我们也只是需要处理最后一个位置就行---------  但也只是beat了66%----

class Solution {
public:
string removeDuplicates(string s, int k) {
vector<pair<char, int>> V;
for(char ch : s){
if(V.empty() || ch != V.back().first){
V.emplace_back(ch,1);
}else{
V.back().second ++;
if(V.back().second == k){
V.pop_back();
}
}
}
string res;
for(auto it : V){
res += string(it.second, it.first);
}
return res;
}
};


----------再仔细看, 其实就只是用stack----------

然而改了后,并没有变快。



Learned: 

不能在循环里用

for(char ch : s){
if(ch == tail->ch){
tail->count ++;
if(tail->count == k){
tail = tail->pre;
tail->next = nullptr;
}
}else{
Node newTail(ch);
tail->next = &newTail;
tail = tail->next;
}
}
而需要用new

You're getting a "stack-use-after-scope" error because of this line in your code:


Node newTail(ch); tail->next = &newTail;

This creates a stack-allocated Node (newTail), then stores a pointer to it in the linked list. But after that iteration of the loop ends, newTail goes out of scope and is destroyed, leaving a dangling pointer.

Sunday, April 6, 2025

1472. Design Browser History. ---M

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 and steps > 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 and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.

 

Example:

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.
browserHistory.back(2);                   // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7);                   // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"

 

Constraints:

  • 1 <= homepage.length <= 20
  • 1 <= url.length <= 20
  • 1 <= steps <= 100
  • homepage and url consist of  '.' or lower case English letters.
  • At most 5000 calls will be made to visit, back, and forward.

A:

关键核心是curCount的定义。 一开始我定义成了pos, 就导致对比res.size()的时候,需要各种加减1.   那样容易出错

class BrowserHistory {
public:
BrowserHistory(string homepage) {
res.clear();
res.push_back(homepage);
curCount = 1;
}

void visit(string url) {
if (curCount < res.size()) {
res.erase(res.begin() + curCount, res.end());
}
res.push_back(url);
curCount++;
}

string back(int steps) {
steps = min(steps, curCount - 1);
curCount -= steps;
return res[curCount - 1];
}

string forward(int steps) {
if (steps > res.size() - curCount) {
steps = res.size() - curCount;
}
curCount += steps;
return res[curCount - 1];
}

private:
vector<string> res;
int curCount; // current valid history count. (use count, to better compare
// with res.size() )
};

/**
* 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);
*/