栈
思路
题目
- 思路
需要定义的量:
numstack,strstack(存储尚未添加进结果集的字符串),resstr(结果字符串),tempnum(暂存num)
- 字符:res添加
- 数字:合并到num
- [:num,res入栈,num,res置零置空
- ]:restr出栈,num出栈,和res合并。
class Solution {
public String decodeString(String s) {
char[] chars = s.toCharArray();
LinkedList<String> strlist = new LinkedList<>();
LinkedList<String> numlist = new LinkedList<>();
StringBuilder strans = new StringBuilder();
StringBuilder numans = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) <= '9' && s.charAt(i) >= '0') {
numans.append(s.charAt(i));
}
else if (s.charAt(i) == '[') {
numlist.addLast(numans.toString());
numans = new StringBuilder();
strlist.addLast(strans.toString());
strans = new StringBuilder();
}
else if (s.charAt(i) == ']') {
int numtemp = Integer.parseInt(numlist.removeLast());
String strtemp = "";
for (int j = 0; j < numtemp; j++) {
strtemp += strans.toString();
}
strans = new StringBuilder(strlist.removeLast() + strtemp);
} else {
strans.append(s.charAt(i));
}
}
return strans.toString();
}
}
计算器
- 思路
非递归的方法是定义两个 栈 来分别存储运算符和运算数。每当遇到一个数直接放进数的栈;每当遇到一个操作符时,要查找之前运算符栈中的元素,按照预先定义好的优先级来进行适当的弹出操作(弹出的同时求出对应的子表达式的值)。 - 步骤
- 数字入栈
- 左括号入栈
- 右括号输出栈顶元素,直到遇到左括号(左括号出站,但不输出)
- 其他运算符,不断去除所有运算优先级>=当前运算符的运算符,输出。最后新的符号入栈。
- 栈中剩下的符号依次输出。
- 代码
std::string convert(const std::string &s) {
std::stack<char> oper;
std::stringstream ss;
ss << s;
std::string t, tmp;
while (ss >> tmp) {
if (isdigit(tmp[0]))
t += tmp + " ";
else if (tmp[0] == '(')
oper.push(tmp[0]);
else if (tmp[0] == ')') {
while (!oper.empty() && oper.top() != '(')
t += std::string(1, oper.top()) + " ",
oper.pop();
oper.pop();
} else {
while (!oper.empty() && level[oper.top()] >= level[tmp[0]])
t += std::string(1, oper.top()) + " ",
oper.pop();
oper.push(tmp[0]);
}
while (!oper.empty()) t += std::string(1, oper.top()) + " ", oper.pop();
return t;
}
int calc(const std::string &s) {
std::stack<int> num;
std::stringstream ss;
ss << s;
std::string t, tmp;
while (ss >> tmp) {
if (isdigit(tmp[0]))
num.push(stoi(tmp));
else {
int b, a;
if (!num.empty()) b = num.top();
num.pop();
if (!num.empty()) a = num.top();
num.pop();
if (tmp[0] == '+') num.push(a + b);
if (tmp[0] == '-') num.push(a - b);
if (tmp[0] == '*') num.push(a * b);
if (tmp[0] == '^') num.push(qpow(a, b));
}
}
return num.top();
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
LinkedList<Integer> queue = new LinkedList<>();
int[] res = new int[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
if (!queue.isEmpty()) {
if ((i - queue.peekFirst()) <= k - 1) {
while ( !queue.isEmpty()&&nums[i] > nums[queue.peekLast()]) {
queue.pollLast();
}
} else {
queue.pollFirst();
while (!queue.isEmpty()&&nums[i] > nums[queue.peekLast()]) {
queue.pollLast();
}
}
}
queue.addLast(i);
if (i >= k - 1) {
res[i-k+1] = nums[queue.peekFirst()];
}
}
return res;
}
}