Basic Calculator - Stack(表达式计算器)
978. Basic Calculator
https://www.lintcode.com/problem/basic-calculator/description
public class Solution {
/**
* @param s: the given expression
* @return: the result of expression
*/
public int calculate(String s) {
// Write your code here
Stack<Integer> stack = new Stack<Integer>();
int result =0;
int number =0;
int sign =1; for(int i =0;i<s.length();i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
number = 10*number + (int)(c-'0');
}else if(c=='+'){
result +=sign*number;
number =0;
sign =1;
}else if(c == '-'){
result += sign * number;
number = 0;
sign = -1;
}else if(c == '('){
stack.push(result);
stack.push(sign);
sign = 1;
result = 0;
}else if(c == ')'){
result += sign* number;
number =0;
result*=stack.pop();
result+=stack.pop();
}
} if(number!=0){
result +=sign*number;
} return result;
}
}
980. Basic Calculator II
https://www.lintcode.com/problem/basic-calculator-ii/description
public class Solution {
/**
* @param s: the given expression
* @return: the result of expression
*/
public int calculate(String s) {
// Write your code here
if(s==null || s.length()==0){
return 0;
} int len = s.length();
Stack<Integer> stack = new Stack<Integer>();
int num =0;
char sign = '+';
for(int i =0;i<len;i++){ if(Character.isDigit(s.charAt(i))){
num = num*10 + s.charAt(i)-'0';
} if((!Character.isDigit(s.charAt(i)) && ' '!=s.charAt(i)) ||i==len-1){
if(sign =='-'){
stack.push(-num);
}
if(sign == '+'){
stack.push(num);
}
if(sign == '*'){
stack.push(stack.pop()*num);
}
if(sign == '/'){
stack.push(stack.pop()/num);
}
sign = s.charAt(i);
num =0;
}
} int re =0;
for(int i:stack){
re +=i;
}
return re; } }
849. Basic Calculator III
https://www.lintcode.com/problem/basic-calculator-iii/description
public class Solution {
/**
* @param s: the expression string
* @return: the answer
*/
public int calculate(String s) {
// Write your code here
if(s==null || s.length()==0){
return 0;
} Stack<Integer> nums = new Stack<Integer>();
Stack<Character> opr = new Stack<Character>(); int num =0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c==' '){
continue;
}
if(Character.isDigit(c)){
num = c-'0';
while(i<s.length()-1 && Character.isDigit(s.charAt(i+1))){
num = num*10+ (s.charAt(i+1)-'0');
i++;
}
nums.push(num);
num =0;
}else if(c=='('){
opr.push(c);
}else if(c==')'){
while(opr.peek()!='('){
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.pop();
}else if(c=='+'||c=='-'||c=='*'||c=='/'){
if(!opr.isEmpty()&&needCalFirst(opr.peek(),c)){
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.push(c);
}
} while(!opr.isEmpty()){
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
} return nums.pop();
} public int calculate(int num1, int num2, char op){
switch(op){
case '+':return num2+num1;
case '-':return num2-num1;
case '*':return num2*num1;
case '/':return num2/num1;
default:return 0;
}
} public boolean needCalFirst(char firstOp, char secondOp){
if(firstOp=='('|| firstOp==')'){
return false;
} if((firstOp=='+'||firstOp=='-')&&(secondOp=='*'||secondOp=='/')){
return false;
} return true;
}
}
368. Expression Evaluation
https://www.lintcode.com/problem/expression-evaluation/description?_from=ladder&&fromId=4
同849 只需注意输入可能不是一个可计算表达式 eg:{'(',')'}
public class Solution {
/**
* @param expression: a list of strings
* @return: an integer
*/
public int evaluateExpression(String[] expression) {
// write your code here
if(expression==null || expression.length==0){
return 0;
} String s = "";
for(int i=0;i<expression.length;i++){
s+=expression[i];
} Stack<Integer> nums = new Stack<Integer>();
Stack<Character> opr = new Stack<Character>(); int num =0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c==' '){
continue;
}
if(Character.isDigit(c)){
num = c-'0';
while(i<s.length()-1 && Character.isDigit(s.charAt(i+1))){
num = num*10+ (s.charAt(i+1)-'0');
i++;
}
nums.push(num);
num =0;
}else if(c=='('){
opr.push(c);
}else if(c==')'){
while(opr.peek()!='('){
if(nums.size()>=2)
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.pop();
}else if(c=='+'||c=='-'||c=='*'||c=='/'){
if(!opr.isEmpty()&&needCalFirst(opr.peek(),c)){
if(nums.size()>=2)
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
}
opr.push(c);
}
} while(!opr.isEmpty()){
if(nums.size()>=2)
nums.push(calculate(nums.pop(),nums.pop(),opr.pop()));
} if(nums.size()>0){
return nums.pop();
} return 0;
} public int calculate(int num1, int num2, char op){
switch(op){
case '+':return num2+num1;
case '-':return num2-num1;
case '*':return num2*num1;
case '/':return num2/num1;
default:return 0;
}
} public boolean needCalFirst(char firstOp, char secondOp){
if(firstOp=='('|| firstOp==')'){
return false;
} if((firstOp=='+'||firstOp=='-')&&(secondOp=='*'||secondOp=='/')){
return false;
} return true;
}
}
Basic Calculator - Stack(表达式计算器)的更多相关文章
- LeetCode OJ:Basic Calculator(基础计算器)
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] 227. Basic Calculator II 基本计算器 II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- [LeetCode] Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] 772. Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] Basic Calculator IV 基本计算器之四
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...
- 227 Basic Calculator II 基本计算器II
实现一个基本的计算器来计算一个简单的字符串表达式. 字符串表达式仅包含非负整数,+, - ,*,/四种运算符和空格 . 整数除法仅保留整数部分. 你可以假定所给定的表达式总是有效的. 一些例子: &q ...
- [LeetCode] 224. Basic Calculator 基本计算器
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] Basic Calculator 基本计算器
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [Swift]LeetCode224. 基本计算器 | Basic Calculator
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
随机推荐
- Spring boot——logback.xml 配置详解(三)<appender>
阅读目录 1 appender 2 encoder 文章转载自:http://aub.iteye.com/blog/1101260,在此对作者的辛苦表示感谢! 回到顶部 1 appender < ...
- 服务器上创建git仓库
1. 在服务器上 su - git ,切换用户 2. 创建一个目录 mkdir test.git ,请注意带上 .git 扩展 3. 切换进入此目录,git init --bare ,初始化裸 ...
- line-height:150% 和 line-height:1.5
line-height属性的细节与大多数CSS属性不同,line-height支持属性值设置为无单位的数字.有无单位在子元素继承属性时有微妙的不同. 有单位(包括百分比)与无单位之间的区别有单位时,子 ...
- awk基础01-基本用法
什么是awk awk 是一门解释型的编程语言,支持条件判断,数组.循环等功能.可用于文本处理.输出格式化的文本信息.执行数学运算.字符串等操作. awk在处理文件时按行进行逐行处理,即 ...
- 23 DesignPatterns学习笔记:C++语言实现 --- 2.4 Composite
23 DesignPatterns学习笔记:C++语言实现 --- 2.4 Composite 2016-07-22 (www.cnblogs.com/icmzn) 模式理解
- Postgresql 分区表 一
Postgres 10 新特性 分区表 http://francs3.blog.163.com/blog/static/40576727201742103158135/ Postgres 10 之前分 ...
- sql2008 获取表结构说明
SELECT 表名 = case when a.colorder=1 then d.name else '' end, 表说明 = case when a.color ...
- solr特点四: SpellCheck(拼写检查)
接下来,我将介绍如何向应用程序添加 “您是不是要找……”(拼写检查). 提供拼写建议 Lucene 和 Solr 很久以前就开始提供拼写检查功能了,但直到添加了 SearchComponent架构之后 ...
- shell查找进程并终止
创建kill.sh文件,内容如下: port= #一.根据端口号查询对应的pid,两种都行 pid=$(netstat -nlp | grep :$port | awk '{print $7}' | ...
- asp.net mvc部分视图的action中获取父级视图信息
RouteData.DataTokens["ParentActionViewContext"]中包含了父级视图的相关信息,如路由等 public ActionResult Chil ...