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 ...
随机推荐
- IntelliJ IDEA版本控制——过滤提交文件
File——>Settings——>File Types 在ignore files and folders中添加提交是需要忽略的文件 例如:*.iml;*.idea;*.gitignor ...
- (广搜)可口可乐 -- hdu -- 1495
链接: http://acm.hdu.edu.cn/showproblem.php?pid=1495 Time Limit: 2000/1000 MS (Java/Others) Memory ...
- [label][OS] 制作 U 盘安装 Windows 7
U盘安装完美的WIN7操作系统教程 [编辑] 请使用正版系统 http://item.jd.com/965031.html 以保证您的电脑信息安全 此教程适用与 win7及win8 准备工作 ...
- web项目开发最佳做法
一个成熟的web项目应该具备以下基础代码或做法 1.前端基础框架: 统一的ajax 通信/表单提交及调用结果弹窗显示 统一的数据验证 统一的数据列表 2.后端基础框架: 统一的异常处理捕获,可针对具体 ...
- Sharepoint安装的几处注意事项
0.sharepoint自带组件安装,无需另下载安装 1.必须安装域(不安装会提示sharepoint 指定的用户是本地账户) 2.域安装后需要在sharepoint设置的数据库账号具有域权限及高级权 ...
- DateUtils常用方法
一.DateUtils常用方法 1.1.常用的日期判断 isSameDay(final Date date1, final Date date2):判断两个时间是否是同一天: isSameInst ...
- python中GUI使用小结
1 先来个简单的 import wx app = wx.App() frm = wx.Frame(None, title="Hello World") frm.Show() app ...
- MYC编译器源码分析之程序入口
前文.NET框架源码解读之MYC编译器讲了MyC编译器的架构,整个编译器是用C#语言写的,上图列出了MyC编译器编译一个C源文件的过程,编译主路径如下: 首先是入口Main函数用来解析命令行参数,读取 ...
- Spring 事务管理案例
事务管理简介 Spring 事务管理有两种方式:一种是编程式事务管理,即通过编写代码实现事物管理,包括定义事务的开始,程序正常执行后的事物提交,异常时进行的事务回滚.另一种是基于AOP技术实现的声 ...
- docker容器日志清理
1.先查看磁盘空间 df -h 2.找到容器的containerId-json.log文件,并清理(治标不治本,log迟早还会大的) 查看各个容器的log文件大小 find /var/lib/dock ...