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 ...
随机推荐
- 在PowerDesigner中设计物理模型1——表和主外键(转)
出处:http://www.cnblogs.com/studyzy/archive/2009/12/15/1624899.html 在PD中建立物理模型由以下几种办法: 直接新建物理模型. 设计好概念 ...
- tab切换代码优化
上次的tab切换的代码里面有很多重复的代码,需要做做优化,把重复的代码用函数封装起来调用. 优化前: <script> //获取id封装成一个函数$()方便调用 function $(id ...
- Hadoop中Comparator原理
在前面的博文<Hadoop中WritableComparable 和 comparator>中,对于WritableComparator说的不够细致,下面说说具体的实现原理! 1.Writ ...
- Web图片编辑控件升级日志-Xproer.ImageEditor
版权所有 2009-2014 荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com 产品首页:http://www.ncmem.com/webplug/image-e ...
- malloc.c
glibc-2.14中的malloc.c源代码,供研究malloc和free实现使用: /* Malloc implementation for multiple threads without lo ...
- dojo和jquery混合使用
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/dojo/1.7 ...
- MFC中的主窗口修改标题
MFC中的主窗口修改标题 如何去掉“无标题”1.在主程序中的InitInstance(): m_pMainWnd->SetWindowText("你要显示的东西如果不想显示置空就行&q ...
- AndroidStudio-Error Loading Project: Cannot load 3 facets
Error Loading Project: Cannot load 3 facets 解决方法,在 File-->Settings-->Plugins-----> 勾选 Andro ...
- centos 安装 tkinter(不只用来做界面,在pylot中也使用)
Python2 [root@binger ~]# yum -y install tkinter tcl-devel tk-devel [root@binger ~]# rpm -qa | grep ^ ...
- jmeter分布式环境
搭建jmeter分布式环境 (1)确定分布式结构,即1台机器部署master.几台机器部署slave? (2)将相同版本的jmeter分别拷贝到这几台机器 (3)修改maste ...