算法總結2

今天練習了一下堆棧的使用:

一、利用堆棧計算逆向波蘭表達式:“3,4,*,1,2,+,+”   》》 3 * 4 + (1+2) = 15

將數字逐一壓入到堆棧中,如果遇到運算符就pop出兩個數組進行計算,並將結果壓回到堆棧中;

首先判斷一下邊界條件:如果讀入的字符是運算符但是堆棧中沒有2個或以上的數組,說明不成立返回false; 

然後根據讀入是數字或操作符做相應的操作;

最後堆上的數字就是最後的結果;

import java.util.Stack;

public class ReversePolishExpr {
	private String string;
	Stack<Integer> stack = new Stack<Integer>();
	
	public ReversePolishExpr(String string){
		this.string = string;
	}
	
	public int isCalculator() throws Exception{
		String[] tem = string.split(",");
		for(int i=0;i<tem.length;i++){
			if(isOperation(tem[i])  && stack.size()<2){
				return -1;
			}
			
			if(isOperation(tem[i])){
				twoNumCal(tem[i]);
			}else{
				stack.push(Integer.valueOf(tem[i]));
			}
		}
		
		return stack.pop();
	}
	
	public boolean isOperation(String s){
		if(s.equals("+") == true || s.equals("-") == true 
				|| s.equals("*") == true ||s.equals("/") == true){
			return true;
		}else{
			return false;
		}
	}
	
	public void twoNumCal(String s) throws Exception{
		int op1 = stack.pop();
		int op2 = stack.pop();
		
		switch(s){
		case "+":
			stack.push(op1+op2);
			break;
		case "-":
			stack.push(op1-op2);
			break;
		case "*":
			stack.push(op1*op2);
			break;
		case "/":
			stack.push(op1/op2);
			break;
		default:
			throw new Exception("Illegal character!");
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 ReversePolishExpr rp = new ReversePolishExpr("3,4,*,1,2,+,+");
	        try {
	            System.out.println("The result of reverse polish express is " + rp.isCalculator());
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	}

}

第二個是返回堆棧當前所有元素中值最大那個元素,時間複雜度爲O(1):

例如stack: 5, 4, 2, 3, 6, 1, 10, 8 返回的就是10

因爲是時間度爲1,所以只能操作一次,那我們就需要考慮空間上能不能有所幫助:

我們同樣申請一個新的堆棧,和一個值maxVal

將序列中的數依次壓入到堆棧中,如果當前壓入的值大於maxVal,更新maxVal並將maxVal壓入到新建的堆棧maxStack中

注意點:在這當中如果有彈出元素,判斷是否是當前最大值,如果是就把從stack和maxStack中彈出,把maxVal值設置成maxStack棧頂上的元素

空間複雜度爲O(n)

package ch04_02;

import java.util.Stack;

public class MaxStack {
	Stack<Integer> stack = new Stack<Integer>();
	private int maxval = 0;
	Stack<Integer> maxStack = new Stack<Integer>();

	public void push(int var){
		if(var > maxval){
			maxval = var;
			maxStack.push(maxval);
		}
		
		stack.push(var);
	}
	
	public int peek(){
		return stack.peek();
	}
	
	public int pop(){
		if(stack.peek() == maxval){
			maxStack.pop();
			maxval = maxStack.peek();
		}
		
		return stack.pop();
	}
	
	public int max(){
		return maxStack.peek();
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MaxStack ms = new MaxStack();
		 ms.push(5);
	        ms.push(4);
	        ms.push(2);
	        ms.push(3);

	        System.out.println("Max Val in stack is : " + ms.max());

	        ms.push(6);
	        ms.push(1);
	        ms.push(10);
	        ms.push(8);
	        System.out.println("Max Val in stack is : " + ms.max());

	        ms.pop();
	        ms.pop();
	        System.out.println("Max Val in stack is : " + ms.max());

	        ms.push(7);
	        System.out.println("Max Val in stack is : " + ms.max());

	}

}

第三個:判斷括號的匹配

這個題只要判斷是“(”還是“ )”,如果是" ( "就把它壓入到堆棧中,如果是“ ) ”就需要判斷了,

首先如果讀取當前的字符是" ) ",判斷堆棧中是否值,如果有就pop(),如果堆棧爲空則判斷爲不匹配。

遍歷完之後如果發現堆棧不爲空,說明還有“(”,判斷爲不匹配

package ch04_03;

import java.util.Stack;

public class stackStringMatch {
	Stack<Character> stack = new Stack<Character>();
	
	private String parents = "";
	
	public stackStringMatch(String parents){
		this.parents = parents;
	}
	
	public boolean isMatch() throws Exception{
		int len = parents.length();
		for(int i=0;i<len;i++){
			if(parents.charAt(i) == '('){
				stack.push(parents.charAt(i));
			}else if(parents.charAt(i) == ')'){
				if(stack.size() == 0 || stack.pop() != '(')//if(stack.size() == 0){
					return false;
			}else{
				throw new Exception("Illegal character");
			}
			
//				}else{
//					stack.pop();
//					//return true;
//				}
		}
		
		if(stack.size() != 0){
			return false;
		}
		
		return true;	
	}
	
	public static void main(String[] args){
		
		String parents = "(())(()))";
		stackStringMatch test = new stackStringMatch(parents);
		try{
			System.out.println(test.isMatch());
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章