栈的简单应用

栈的特点是后进先出。栈的应用场景与这个特点息息相关。栈的实现在前一篇博文中栈的实现。
1. 数制转换
N=(N div d) x d+N mod d
其中, div 相除取整, mod 相除取余

public class NumerationSystemConversion {
    private final static NumerationSystemConversion conveter = new NumerationSystemConversion();
    // 任意两进制之间进行转换
    public String convert(String sourceNum, int sourceSystem, int destinationSystem) {
        String rs = "";
        String tmpNum ="";


        if(sourceSystem==destinationSystem){
            return sourceNum;
        }


        tmpNum =sourceSystem==10?sourceNum:convertOtherTo10(sourceNum, sourceSystem);
        rs=destinationSystem==10?tmpNum:convert10ToOther(tmpNum, destinationSystem);

        switch(destinationSystem){
        case 8: 
            rs="0"+rs;
            break;
        case 16:
            rs="0x"+rs;
            break;
        }
        return rs;
    }


    // 从其他进制转换为十进制
    public String convertOtherTo10(String numStr, int sourceSystem) {
        numStr=handleSymbol(numStr,sourceSystem);
        char[] nums = numStr.toCharArray();
        int total = 0;
        int mi = nums.length - 1;
        for (char num : nums) {
            total += Character.getNumericValue(num) * (int) Math.pow(sourceSystem, mi);
            mi--;
        }


        return String.valueOf(total);
    }

    // 将十进制转为其它 进制
    public String convert10ToOther(String numStr, int destinationSystem) {
        Stack rs = new Stack();
        int num;
        try {
            num = Integer.parseInt(numStr);
        } catch (NumberFormatException e) {
            throw new RuntimeException("number format is wrong ,please check !");
        }

        int div = 0;
        int mod = 0;
        do {
            div = num / destinationSystem;
            mod = num % destinationSystem;
            rs.push(mod);
            num = div;
        } while (div > 0);

        String result = "";
        while (!rs.isEmpty()) {
            int x = rs.pop();
            result += convertBit(x);
        }
        return result;

    }

    private String convertBit(int a) {
        if (a < 10) {
            return String.valueOf(a);
        }
        char x = (char) (87 + a);
        return String.valueOf(x);
    }

    public String handleSymbol(String numStr, int sourceSystem){
        switch (sourceSystem) {
        case 8:
            if (numStr.startsWith("0"))
                numStr = numStr.substring(1);
            break;
        case 16:
            if (numStr.toLowerCase().startsWith("0x"))
                numStr = numStr.toLowerCase().substring(2);
            break;
        default:
        }
        return numStr;
    }


    public static void main(String[] args) {
        printResult("0xa1",16,10);
        printResult("161",10,8);
        printResult("0241",8,16);
        printResult("011",8,2);

    }

    public static void  printResult(String source,int from,int to){
        System.out.println(String.format("从  %d进制 转换成  %d进制,       %s => %s", from,to,source,conveter.convert(source, from, to)));
    }

}
  1. 括号匹配的校验
    检验括号是否匹配可用“期待的急迫程度”这个概念。
public class BracketChecker {
    static Map map;
    Stack stack;
    static {
        map = new HashMap();
        map.put("{", "}");
        map.put("[", "]");
        map.put("(", ")");

    }

    public boolean check(String exp) {
        if (exp == null || exp.length() == 0) {
            return true;
        }
        stack = new Stack();
        for (int i = 0; i < exp.length(); i++) {
            String c = exp.substring(i, i + 1);
            if (map.containsKey(c)) {
                stack.push(c);
            }
            if (map.containsValue(c)) {
                if (!c.equals(map.get(stack.pop()))) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        BracketChecker checker = new BracketChecker();

        System.out.println(checker.check("{}[(]"));
    }
}
  1. 行编辑程序问题
    问题描述:
    一个简单的行编辑功能是:接受用户从终端输入的数据,并存入用户数据区。
    不是用户输入的每个字符都放入数据区,而是有一个缓冲区

import datastructure.stack.impl.Stack;

public class InputEditor {



    //我们约定#为删除一个字符
    private String input(String in){
        String out="";
        if(in==null||in.length()==0){
            return out;
        }
        Stack inStack=new Stack();
        for(int i=0;i<in.length();i++){
            String c=in.substring(i, i+1);
            if("#".equals(c)){
                inStack.pop();
            }else{
                inStack.push(c);
            }
        }
        while(!inStack.isEmpty()){
            out=inStack.pop()+out;
        }
        return out;
    }

    public static void main(String[] args) {
        InputEditor editor=new InputEditor();
        System.out.println(editor.input("12#3##5678"));

    }

}

你可能感兴趣的:(数据结构与算法,栈)