Skip to content

Commit

Permalink
Sep14: string & stack [E]
Browse files Browse the repository at this point in the history
remember that string can also use the stack ops.
  • Loading branch information
aucker committed Sep 14, 2024
1 parent de55fd8 commit 58d862e
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
33 changes: 33 additions & 0 deletions daily/Sep13.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <deque>
#include <iostream>
using namespace std;

class Solution {
public:
int maximumRobots(vector<int>& chargeTimes, vector<int>& runningCosts,
long long budget) {
int ans = 0, le = 0;
long long sum = 0;
deque<int> dq;
for (int ri = 0; ri < chargeTimes.size(); ri++) {
// enque
while (!dq.empty() && chargeTimes[ri] >= chargeTimes[dq.back()]) {
dq.pop_back();
}
dq.push_back(ri);
sum += runningCosts[ri];

// deque
while (!dq.empty() &&
chargeTimes[dq.front()] + (ri - le + 1) * sum > budget) {
if (dq.front() == le) {
dq.pop_front();
}
sum -= runningCosts[le++];
}

ans = max(ans, ri - le + 1);
}
return ans;
}
};
63 changes: 63 additions & 0 deletions daily/Sep14.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include <iostream>
using namespace std;

class Solution {
public:
string removeStars1(string s) {
string ans;
stack<char> stk;
for (char c : s) {
if (c == '*') {
stk.pop();
} else {
stk.push(c);
}
}
while (!stk.empty()) {
char c = stk.top();
ans.push_back(c);
stk.pop();
}
std::reverse(ans.begin(), ans.end());
return ans;
}

string removeStars2(string s) {
string ans;
deque<char> dq;
for (char c : s) {
if (c == '*') {
dq.pop_back();
} else {
dq.push_back(c);
}
}

while (!dq.empty()) {
ans.push_back(dq.front());
dq.pop_front();
}
return ans;
}

/**
* @brief remove stars in a string
* Use the stack to solve this problem, however, use stack or deque
* is a little bit complex
* Remember that `string` also has the `pop_back()` api, just use string.
*
* @param s
* @return string
*/
string removeStars3(string s) {
string ans;
for (char c : s) {
if (c == '*') {
ans.pop_back();
} else {
ans += c;
}
}
return ans;
}
};
26 changes: 26 additions & 0 deletions daily/Sep8.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <vector>

class Solution {
public:
vector<int> sortedSquares(vector<int> nums) {
int len = nums.size();
for (int i = 0; i < len ; i++) {
nums[i] = nums[i] * nums[i];
}

vector<int> ans(len, 0);
int le = 0, ri = len - 1;
int pivot = len - 1;
while (le <= ri) {
if (nums[le] > nums[ri]) {
ans[pivot] = nums[le]; // get larger
le++;
} else {
ans[pivot] = nums[ri];
ri--;
}
pivot--;
}
return ans;
}
}

0 comments on commit 58d862e

Please sign in to comment.