【名词解释】
"1#1#+"
2
1#1#+这个后缀表达式表示的式子是1+1,结果为2
"12#3#+15#*"
225
12#3#+15#*这个后缀表达式表示的式子是(12+3)*15,结果为225
"1#1#4#5#-*+1#4#*+"
4
#include <errno.h>
// #define OK 1
// #define ERROR -1
// #define MEMORY_OVERFLOW -2
typedef enum { OK = 1, ERROR = -1, MEMORY_OVERFLOW = -2 } Status;
#define NOT !
#define DEFAULT_CAPACITY 8
#define InitStack(S) __InitStack(S, DEFAULT_CAPACITY)
typedef long long LL;
// ==================== 顺序栈存储结构表示与实现 ====================
typedef LL SElemType;
typedef struct {
SElemType* base;
SElemType* top;
size_t capacity;
} SqStack;
Status __InitStack(SqStack* S, int initialCapacity) {
if (initialCapacity < 1) {
fprintf(stderr,
"__InitStack ERROR: The initialCapacity %d Must be > 0!",
initialCapacity);
return ERROR;
}
if (!((*S).base = (SElemType*) malloc(initialCapacity * sizeof(SElemType)))) {
fprintf(stderr,
"__InitStack Memory Overflow: %s\n",
strerror(errno));
exit(MEMORY_OVERFLOW);
}
(*S).top = (*S).base;
(*S).capacity = initialCapacity;
return OK;
}
int StackEmpty(SqStack* S) {
return (*S).top == (*S).base;
}
int StackFull(SqStack* S) {
return (*S).top - (*S).base == (*S).capacity;
}
size_t StackLength(SqStack* S) {
return (*S).top - (*S).base;
}
void __large_capacity(SqStack* S) {
if (!((*S).base = (SElemType*)
realloc((*S).base, ((*S).capacity << 1) * sizeof(SElemType)))) {
fprintf(stderr,
"__large_capacity Memory Overflow: %s\n",
strerror(errno));
exit(MEMORY_OVERFLOW);
}
(*S).top = (*S).base + (*S).capacity;
(*S).capacity <<= 1;
}
Status Push(SqStack* S, SElemType e) {
if (StackFull(S))
__large_capacity(S);
*(*S).top++ = e;
return OK;
}
Status Pop(SqStack* S, SElemType* e) {
if (StackEmpty(S)) {
fputs("Pop ERROR: The stack is empty!\n", stderr);
return ERROR;
}
*e = *--(*S).top;
return OK;
}
Status DestroyStack(SqStack* S) {
free((*S).base);
(*S).top = NULL;
return OK;
}
// ==================== 顺序栈存储结构表示与实现 ====================
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
long long legalExp(char* str) {
SqStack S;
InitStack(&S);
LL num = 0, n1, n2;
while (*str) {
switch (*str) {
case '+':
Pop(&S, &n2); Pop(&S, &n1);
Push(&S, n1 + n2);
break;
case '-':
Pop(&S, &n2); Pop(&S, &n1);
Push(&S, n1 - n2);
break;
case '*':
Pop(&S, &n2); Pop(&S, &n1);
Push(&S, n1 * n2);
break;
case '#':
Push(&S, num);
num = 0;
break;
default: // numerical
num = num * 10 + *str - 48;
break;
}
++str;
}
LL ans;
Pop(&S, &ans);
DestroyStack(&S);
return ans;
} long long legalExp(string str) {
stack<long long> operand;
long long a=0;
for(int i=0;i<str.length();i++) {
if(str[i]>='0'&&str[i]<='9')
a=a*10+str[i]-'0';
switch(str[i]) {
case '#' :
if(str[i+1]>='0'&&str[i+1]<='9') {
operand.push(a);
a=0;
}
break;
case '+': a=operand.top()+a; break;
case '-': a=operand.top()-a; break;
case '*': a=operand.top()*a; break;
default: break;
}
if(str[i]=='+'||str[i]=='-'||str[i]=='*') {
operand.pop();
if(i+1<str.length()&&str[i+1]>='0'&&str[i+1]<='9') {
operand.push(a);
a=0;
}
}
}
return a;
}
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
public long legalExp (String str) {
Stack<Long> stack = new Stack<>();
StringBuilder numBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '#') {
// 遇到结束符,将构建的数字入栈
if (numBuilder.length() > 0) {
long num = Long.parseLong(numBuilder.toString());
stack.push(num);
numBuilder.setLength(0); // 重置用于下一个数字
}
} else if (c == '+' || c == '-' || c == '*') {
// 遇到运算符,弹出两个操作数进行计算
long b = stack.pop();
long a = stack.pop();
long result = 0;
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
}
stack.push(result);
} else {
// 数字字符,继续构建数字(包括可能的负号)
numBuilder.append(c);
}
}
// 栈顶元素即为最终结果
return stack.pop();
}
}
#include<stack>
#include<string>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
long long legalExp(string str) {
// write code here
int pos_end=-1;
stack<long long>s;
for(int i=0;i<str.size();i++){
if(str[i]=='#'){
string nums;
for(int j=pos_end+1;j<i;j++){
if(str[j]>='0'&&str[j]<='9'){
nums+=str[j];}
}
long long numint=stoi(nums);
s.push(numint);
pos_end=i;
}
else if(str[i]=='+'||str[i]=='-'||str[i]=='*'){
long long num1=s.top();s.pop();
long long num2=s.top();s.pop();
if(str[i]=='+'){
s.push(num1+num2);
}
else if(str[i]=='-'){
s.push(num2-num1);
}
else if(str[i]=='*'){
s.push(num2*num1);
}
}
}
return s.top();
}
}; import re # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 给定一个后缀表达式,返回它的结果 # @param str string字符串 # @return long长整型 # class Solution: def legalExp(self , str ): # write code here s = re.findall(r'\d+|[+*#\-]', str) new_s = [] list_s = [] for j in s: if j == "#": continue else: new_s.append(j) res = 0 for i in new_s: if i == "+": res = int(list_s[-2]) + int(list_s[-1]) list_s[-2] = int(res) list_s.pop() elif i == "-": res = int(list_s[-2]) - int(list_s[-1]) list_s[-2] = int(res) list_s.pop() elif i == "*": res = int(list_s[-2]) * int(list_s[-1]) list_s[-2] = int(res) list_s.pop() else: list_s.append(i) return res
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
#include <stdio.h>
#include <stdlib.h>
long long legalExp(char* str ) {
// write code here
long long rus = 0, tmp_num=0;
int tmp_len = 0, top = 0;
char tmp[20], c = str[0];
long long *stack = (long long *)malloc(sizeof(long long) * 250000);
while (c != '\0') {
if(c == '#'){
for(int i = 0; i < tmp_len; i++){
tmp_num = tmp_num * 10 + (tmp[i] - '0');
}
stack[top++] = tmp_num;
tmp_num = 0;
tmp_len = 0;
}
else if(c == '+'){ stack[top-2] += stack[top-1]; top--;}
else if(c == '-'){ stack[top-2] -= stack[top-1]; top--;}
else if(c == '*'){ stack[top-2] *= stack[top-1]; top--;}
else tmp[tmp_len++] = c;
c = *(++str);
}
rus = stack[0];
free(stack);
stack = NULL;
return rus;
} class Solution:
def legalExp(self , chars:str ):
# write code here
stack = []
ops = {
'+': lambda x, y: x + y,
'*': lambda x, y: x * y,
'-': lambda x, y: x - y,
}
curr = ""
for char in chars:
if char == "#":
stack.append(int(curr))
curr = ""
elif char in ops:
res = ops[char](stack.pop(-2),stack.pop(-1))
stack.append(res)
else:
curr += char
return stack[0] #
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 给定一个后缀表达式,返回它的结果
# @param str string字符串
# @return long长整型
#
class Solution:
def legalExp(self , str ):
# write code here
def apply_op(a,b,op):
if op == "+":return a+b
if op == "-":return a-b
if op == "*":return a*b
stack = []
i = 0
while i < len(str):
if str[i].isdigit():
num = 0
while i < len(str) and str[i].isdigit():
num = num *10 + int(str[i])
i += 1
stack.append(num)
elif str[i] == "#":
i += 1
elif str[i] in ("+","-","*"):
num1 = stack.pop()
num2 = stack.pop()
op = str[i]
stack.append(apply_op(num2,num1,op))
i += 1
return int(stack[0])
if __name__ == "__main__":
s = str(input().strip().replace('"',''))
print(Solution().legalExp(s))