leetcode: basic caculator
2015-06-19 11:20
495 查看
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.
Show Tags
Have you met this question in a real interview? Yes No
Discuss
我的提交:
下面转自http://blog.csdn.net/u012925008/article/details/46480653
转为前缀计算
转为后缀计算
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.
Show Tags
Have you met this question in a real interview? Yes No
Discuss
我的提交:
public class Solution { public int calculate(String s) { Stack<Integer> num = new Stack<Integer>(); Stack<Character> op = new Stack<Character>(); boolean isNum = false; int length = s.length(); char c,p; int val = 0; for(int i = 0; i<length; i++){ c = s.charAt(i); val = 0; if(Character.isDigit(c)){ while(i<length&&s.charAt(i)<='9'&&s.charAt(i)>='0'){ c = s.charAt(i); val= val*10 + (c-'0'); i++; } num.push(val); i--; } else if(c =='('){ op.push(c); } else if(c == ')'){ while((p=op.pop())!='('){ int n1 = num.pop(); int n2 = num.pop(); val = cacu(n2,n1,p); num.push(val); } } else if (c=='+'||c =='-'){ if(op.isEmpty()|| '(' == op.peek()){ op.push(c); } else { p = op.pop(); int n1 = num.pop(); int n2 = num.pop(); val = cacu(n2,n1,p); num.push(val); op.push(c); } } else{ } } while(!op.isEmpty()){ c = op.pop() ; int n1 = num.pop(); int n2 = num.pop(); val = cacu(n2,n1,c); num.push(val); } return num.pop(); } int cacu(int n1,int n2, char p){ if(p == '+') return n1+n2; else return n1-n2; } }
下面转自http://blog.csdn.net/u012925008/article/details/46480653
转为前缀计算
class ExpressionTransformation { public: string trans_to_prefix_expression_to_s(string); // 将得到的表达式转化为前缀表达式 long long int calculate_from_prefix_expression(); // 根据前缀表达式计算值 private: vector<string> ans_vector_pre; // 存放前缀表达式,这样放可以区分超过1位的数字 string pre_string; // 存放前缀表达式 }; inline int prior(char op) { // 计算优先级函数 if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/' || op == '%') { return 2; } else { return 0; } } long long int string_to_int(string in) { // 将输入的字符串转化为相应数字函数 char s[50]; for (int i = 0; i < 50; i++) { s[i] = '\0'; } for (int i = 0; i < in.size(); i++) { s[i] = in[i]; } long long int ans; sscanf(s, "%lld", &ans); return ans; } string deleteBlank(string in) { string ans; int size = in.size(); for (int i = 0; i < size; i++) { if (in[i] != ' ') ans.push_back(in[i]); } return ans; } string ExpressionTransformation::trans_to_prefix_expression_to_s(string original_in) { stack<char> op; vector<string> temp_vector_pre; string in; for (int i = 0; i < original_in.size(); i++) { // 进行前缀表达式转化的时候实现要对表达式做倒序处理 in.push_back(original_in[original_in.size() - 1 - i]); } for (int i = 0; i < in.size();) { // 但是直接倒序会将表达式中的数字倒过来,比如123到321,所以要还原 if ('0' <= in[i] && in[i] <= '9') { string temp_reverse_part; int j; for (j = i; j < in.size() && '0' <= in[j] && in[j] <= '9'; j++) {} for (int k = j - 1; k >= i; k--) { temp_reverse_part.push_back(in[k]); } for (int k = i; k < j; k++) { in[k] = temp_reverse_part[k - i]; } i = j; } else { i++; } } for (int i = 0; i < in.size();) { char c = in[i]; if ('0' <= c && c <= '9') { // 是数字直接插入 string num; int j; for (j = i; j < in.size() && '0' <= in[j] && in[j] <= '9'; j++) { num.push_back(in[j]); } temp_vector_pre.push_back(num); i = j; } else { if (c == ')') { // 闭括号直接插入 op.push(c); } else { if (c == '(') { // 开括号就将操作符栈中的操作符输出,直到遇上闭括号 while (op.top() != ')') { string temp; temp.push_back(op.top()); temp_vector_pre.push_back(temp); op.pop(); } op.pop(); } else { if (op.empty()) { // 操作符是空直接插入 op.push(c); } else { if (prior(c) >= prior(op.top())) { // 这里跟后缀表达式有细微区别 op.push(c); } else { while (!op.empty() && prior(c) < prior(op.top())) { // 同上 string temp; temp.push_back(op.top()); temp_vector_pre.push_back(temp); op.pop(); } op.push(c); } } } } i++; } } while (!op.empty()) { // 注意操作符栈里还有东西要输出 string temp; temp.push_back(op.top()); temp_vector_pre.push_back(temp); op.pop(); } ans_vector_pre.clear(); // 输出结果还要再倒序 for (int i = 0; i < temp_vector_pre.size(); i++) { ans_vector_pre.push_back(temp_vector_pre[temp_vector_pre.size() - 1 - i]); } pre_string.clear(); // 转化为string输出 for (int i = 0; i < ans_vector_pre.size(); i++) { pre_string += ans_vector_pre[i]; } return pre_string; } long long int ExpressionTransformation::calculate_from_prefix_expression() { //这里的计算类似于后缀表达式,但是要从后往前,并且注意顺序 stack<long long int> ans_pre; for (int i = ans_vector_pre.size() - 1; i >= 0; i--) { long long int x, y; if ('0' <= ans_vector_pre[i][0] && ans_vector_pre[i][0] <= '9') { ans_pre.push(string_to_int(ans_vector_pre[i])); } else { x = ans_pre.top(); // 这里相当于+xy也就是x+y ans_pre.pop(); y = ans_pre.top(); ans_pre.pop(); if (ans_vector_pre[i][0] == '+') { ans_pre.push(x + y); } else if (ans_vector_pre[i][0] == '-') { ans_pre.push(x - y); } else if (ans_vector_pre[i][0] == '*') { ans_pre.push(x * y); } else if (ans_vector_pre[i][0] == '/') { ans_pre.push(x / y); } else { ans_pre.push(x % y); } } } return ans_pre.top(); } class Solution { public: int calculate(string s) { ExpressionTransformation e; s = deleteBlank(s); e.trans_to_prefix_expression_to_s(s); int preAns = e.calculate_from_prefix_expression(); return preAns; } };
转为后缀计算
class ExpressionTransformation { public: string trans_to_postfix_expression_to_s(string); // 将得到的表达式转化为后缀表达式 long long int calculate_from_postfix_expression(); // 根据后缀表达式计算值 private: vector<string> ans_vector_post; // 存放后缀表达式 string post_string; // 存放后缀表达式 }; inline int prior(char op) { // 计算优先级函数 if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/' || op == '%') { return 2; } else { return 0; } } long long int string_to_int(string in) { // 将输入的字符串转化为相应数字函数 char s[50]; for (int i = 0; i < 50; i++) { s[i] = '\0'; } for (int i = 0; i < in.size(); i++) { s[i] = in[i]; } long long int ans; sscanf(s, "%lld", &ans); return ans; } string deleteBlank(string in) { string ans; int size = in.size(); for (int i = 0; i < size; i++) { if (in[i] != ' ') ans.push_back(in[i]); } return ans; } string ExpressionTransformation::trans_to_postfix_expression_to_s(string in) { stack<char> op; // 操作符栈 ans_vector_post.clear(); // 后缀表达式存放数组 for (int i = 0; i < in.size();) { char c = in[i]; if ('0' <= c && c <= '9') { // 是数字直接插入 string num; int j; for (j = i; j < in.size() && '0' <= in[j] && in[j] <= '9'; j++) { num.push_back(in[j]); } ans_vector_post.push_back(num); i = j; } else { if (c == '(') { // 是开括号直接插入 op.push('('); } else { if (c == ')') { // 是闭括号就把原本栈中的运算符都输出,直到遇到开括号,注意开括号要丢弃 while (op.top() != '(') { string temp; temp.push_back(op.top()); ans_vector_post.push_back(temp); op.pop(); } op.pop(); } else { // 假如是加减乘除取余 if (op.empty()) { // 操作符栈是空就直接插入 op.push(c); } else { // 如果扫描到的运算符优先级高于栈顶运算符则,把运算符压入栈。否则的话,就依次把栈中运算符弹出加到数组ans的末尾,直到遇到优先级低于扫描到的运算符或栈空,并且把扫描到的运算符压入栈中 if (prior(c) > prior(op.top())) { op.push(c); } else { while (!op.empty() && prior(c) <= prior(op.top())) { string temp; temp.push_back(op.top()); ans_vector_post.push_back(temp); op.pop(); } op.push(c); } } } } i++; } } while (!op.empty()) { // 注意把操作符栈中的剩余操作符输出 string temp; temp.push_back(op.top()); ans_vector_post.push_back(temp); op.pop(); } post_string.clear(); // 构造string并返回 for (int i = 0; i < ans_vector_post.size(); i++) { post_string += ans_vector_post[i]; } return post_string; } long long int ExpressionTransformation::calculate_from_postfix_expression() { //利用栈对后缀表达式求值,直接从后缀表达式的左往右扫描,遇到数字放入栈中,遇到字符就把栈顶的两个数字拿出来算,然后再放进栈 stack<long long int> ans_post; for (int i = 0; i < ans_vector_post.size(); i++) { long long int x, y; if ('0' <= ans_vector_post[i][0] && ans_vector_post[i][0] <= '9') { ans_post.push(string_to_int(ans_vector_post[i])); } else { y = ans_post.top(); // 注意顺序,这里好比xy+就是x+y ans_post.pop(); x = ans_post.top(); ans_post.pop(); if (ans_vector_post[i][0] == '+') { ans_post.push(x + y); } else if (ans_vector_post[i][0] == '-') { ans_post.push(x - y); } else if (ans_vector_post[i][0] == '*') { ans_post.push(x * y); } else if (ans_vector_post[i][0] == '/') { ans_post.push(x / y); } else { ans_post.push(x % y); } } } return ans_post.top(); } class Solution { public: int calculate(string s) { ExpressionTransformation e; s = deleteBlank(s); e.trans_to_postfix_expression_to_s(s); int postAns = e.calculate_from_postfix_expression(); return postAns; } };
相关文章推荐
- 穿越到 1983 年学习 BASIC
- FREEBASIC 编译可被python调用的dll函数示例
- ColdFusionMX 编程指南 ColdFusionMX Basic Tag编程
- 实用的利用 CSS + <em>标签 来完成一个三角形的制作
- JavaScript中“+”的陷阱深刻理解
- ASP + Serv-u 实现FTP的代码
- css静态滤镜 + A:Hover 效果第1/3页
- javascript中加号(+)操作符的一些神奇作用
- Python列表append和+的区别浅析
- windows+ubuntu双系统重新安装windows后的引导修复 3ff0
- XBMC on ATV2 + XBMoteC(remote app)[XBMC遠端遙控器]
- Spring + Struts2 + Hibernate整合
- postfix + amavisd-new + clamav + spamassassin
- 配置Apache服务的basic和digest摘要认证
- cacti + nagios + npc 整合部署
- URL中带加号(+)的处理
- Fedora安装 win7 32b 安装fedora x64 dvd
- A basic Particles System(1)
- A basic Particles System(2)