申明:这是一个渣渣的伪技术博客,并没有什么学习价值。。。
题目:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
分析:题目要求实现一个能运算带()+-四种符号的表达式的函数。题目本身并不难,用栈的结构,如果遇到运算符,比当前栈顶运算符优先级高就进栈,否则就退栈。将表达式变成逆波兰式,在对逆波兰式进行计算。
由于我刚刚学了数据结构,所以并不想走C++的捷径,自定义了一个STACK的数据结构,再由于本人十分的拿衣服,一开始是用的顺序表,结果在Leecode上跑的时候,由于数组数组开的不够大,结果各种过不了。开了500的数组,在长度为5000的样例卡了,扩展到5000,在长度为50000的样例卡了,扩展到50000,在长度为500000的样例卡了,扩展到500000。。。申请不了如此大的内存空间!
可以想象我的内心是奔溃的,这是非改链表不可了。于是我又把它改成了单链表,这下总行了吧,然而运行超时。。。运行超时。。。运行超时。。。擦掉眼泪我又把数据结构改成了双向链表,终于AC了!!!所说整整花了四个小时,然而还是热泪盈眶。。。但是运行的时间超级慢,代码很长,所以如何改进还有待学习。(然而博主现在并木有时间。。。)
代码如下:
#include <iostream> #include <string> #include <sstream> using namespace std; typedef struct elem { int data; bool isop;//操作符为true struct elem* previous; struct elem* next; elem(int d,bool b) { data = d; isop = b; next = NULL; previous=NULL; } }; typedef struct STACK { elem* bottom; elem* top; int length; void init() { bottom=NULL; top=NULL; } void push(elem e) { if (bottom == NULL) { top = new elem(e.data,e.isop); bottom = top; return; } elem* p; p = new elem(e.data,e.isop); p->previous = top; top->next = p; top = top->next; } void pop(elem* &e) { elem* p = bottom; if (p==NULL) return; if (bottom==top) { e=top; bottom=NULL; top=NULL; return; } e=top; top=top->previous; top->next=NULL; e->previous=NULL; return; } }; class Solution { public: int calculate(string a) { int len=a.length(); STACK op; op.init(); STACK ex; ex.init(); elem* e; for (int i=0; a[i]!='