问题如下
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
例子,即数组输入字符串 2,1,+,3,* 输出9
java代码:
package leetcode2.EvaluateReversePolishNotatio;
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> numbers = new Stack<Integer>();
int l = tokens.length;
String operators = "+-*/";
for (int i=0; i<l; i++){
if (operators.contains(tokens[i])){
int newN;
int newN1 = numbers.pop();
int newN2 = numbers.pop();
if (tokens[i].equals("+")){
newN = newN1 + newN2;
}
else if (tokens[i].equals("-")){
newN = newN2 - newN1;
}
else if (tokens[i].equals("*")){
newN = newN1 * newN2;
}
else{
newN = newN2 / newN1;
}
numbers.push(newN);
}
else{
numbers.push(Integer.parseInt(tokens[i]));
}
}
return numbers.get(0);
}
}
测试代码:
package leetcode2.EvaluateReversePolishNotatio;
public class Cilent {
public static void main(String []args){
Solution sol = new Solution();
String array[] = {"3","1","+","3", "*"};
int i=sol.evalRPN(array);
System.out.print(i);
}
}
总结栈的定义代码:
package leetcode2.stackInfo;
public class Stack {
private int maxSize;
private int top;
private char []stack;// point to the current;
public Stack(int maxSize){
this.maxSize=maxSize;
this.top=-1;
this.stack=new char[maxSize];
}
public void push(char c){// push stack;
stack[++top]=c;
}
public char pop(){// pop stack;
return stack[top--];
}
public boolean isEmpty(){
return top==-1;
}
public char getTop(){
return stack[top];
}
}
在回答oj问题时直接调用java,util.Stack;
这里也加上中缀后缀的转换算法:处理算法
package leetcode2.stackInfo;
public class Process {
private String input;
private String output="";
private Stack stack;
public Process(String input){
this.input=input;
stack=new Stack(input.length());
}
public String doTrans(){
for(int i=0;i<input.length();i++){
char ch=input.charAt(i);// get the char
switch(ch){ //the core
case '*':
case '/':
while(!stack.isEmpty() && (stack.getTop() == '*' || stack.getTop() == '/')){
output+=stack.pop();
}//while
stack.push(ch);
break;
case '+':
case '-':
while(!stack.isEmpty() && stack.getTop()!='('){
output+=stack.pop();
}//while
stack.push(ch);
break;
case '(':
stack.push(ch);
break;
case ')':
char temp;
while(!stack.isEmpty() && ((temp=stack.getTop())!='(')){
output+=temp;
}
break;
default:
output+=ch;
break;
}//switch
}//for
while(!stack.isEmpty()){
output+=stack.pop();
}
return output;
}//doTrans
}//process
测试代码:
package leetcode2.stackInfo;
public class client {
public static void main(String []args){
String index="1+2*3-6/3";
Process pro= new Process(index);
String string=pro.doTrans();
System.out.println(string);
}
}