Skip to content

Commit 416d867

Browse files
committed
Add C++ solutions for day 3 and day 4.
1 parent 8335b2b commit 416d867

2 files changed

+114
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
string decodeString(string s) {
9+
deque<int> numStack;
10+
deque<string> strStack;
11+
string resStr;
12+
13+
int n = s.size();
14+
for (int i = 0; i < n; i++)
15+
{
16+
char ch = s[i];
17+
if (isdigit(ch))
18+
{
19+
int digit = ch - '0';
20+
while (i < n - 1 && isdigit(s[i + 1]))
21+
{
22+
digit = digit * 10 + s[i + 1] - '0';
23+
i++;
24+
}
25+
numStack.push_front(digit);
26+
}
27+
else if (ch == '[')
28+
{
29+
strStack.push_front(resStr);
30+
resStr.clear();
31+
}
32+
else if (ch == ']')
33+
{
34+
string tmp = strStack.front();
35+
strStack.pop_front();
36+
int repeatCount = numStack.front();
37+
numStack.pop_front();
38+
for (int j = 0; j < repeatCount; j++)
39+
tmp.append(resStr);
40+
41+
resStr = tmp;
42+
}
43+
else resStr.push_back(ch); // 直接取出来放进结果字符串中
44+
}
45+
return resStr;
46+
}
47+
};
48+
49+
// Test
50+
int main()
51+
{
52+
Solution sol;
53+
string s = "2[abc]3[cd]ef";
54+
auto res = sol.decodeString(s);
55+
// 期望的结果: "abcabccdcdcdef"
56+
cout << res << endl;
57+
58+
return 0;
59+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
class CustomStack {
7+
public:
8+
vector<int> stack;
9+
int size;
10+
11+
CustomStack(int maxSize) {
12+
stack.resize(maxSize);
13+
size = 0;
14+
}
15+
16+
void push(int x) {
17+
if (size < stack.size())
18+
{
19+
stack[size] = x;
20+
size++;
21+
}
22+
}
23+
/* 弹出栈顶元素,并返回栈顶的值,或栈为空时返回 -1 */
24+
int pop() {
25+
int res = -1;
26+
if (size > 0)
27+
{
28+
size--;
29+
res = stack[size];
30+
}
31+
32+
return res;
33+
}
34+
/* 栈底的 k 个元素的值都增加 val 。如果栈中元素总数小于 k ,则栈中的所有元素都增加 val */
35+
void increment(int k, int val) {
36+
for (int i = 0; i < min(k, size); i++)
37+
stack[i] += val;
38+
}
39+
};
40+
41+
// Test
42+
int main()
43+
{
44+
int maxSize = 5;
45+
CustomStack *customStack = new CustomStack(3); // Stack 初始化为 [], 长度为3
46+
customStack->push(1); // 栈变为 [1]
47+
customStack->push(2); // 栈变为 [1, 2]
48+
customStack->push(8); // 栈变为 [1, 2, 8]
49+
int val1 = customStack->pop(); // 返回栈顶值8, 栈变为 [1, 2]
50+
cout << val1 << endl;
51+
52+
customStack->increment(2, 100); // 栈变为 [101, 102]
53+
54+
return 0;
55+
}

0 commit comments

Comments
 (0)