1. 程式人生 > >LintCode堆疊題總結

LintCode堆疊題總結

這篇是基於我之前的一篇文章的:LintCode資料結構題 那篇文章介紹了基本的堆疊實現以及一些基本的應用。現在來看一下更多的題目和應用來擴充套件一下對堆疊的實踐。

要求對錶達式進行展開。比如 s = 3[2[ad]3[pf]]xyz, return adadpfpfpfadadpfpfpfadadpfpfpfxyz。這道題可以用一個棧Stack來解決。然後通過分支判斷來處理不同的情況。需要注意的是數字可以是兩位數三位數等等,所以要對數字進行整合。

從左往右掃描字串,基本的邏輯如下:

1)如遇到數字,則把字元轉換為數字

2)如遇到左括號,則把數字入棧

3)如遇到右括號,則把棧內的字串拿出來做一個轉換,再放回到棧中

4)如遇到普通的字元,則入棧

舉個例子,假如字串是2[2[a]2[p]]x,則轉換過程如下圖所示:


public class Solution {
    /**
     * @param s  an expression includes numbers, letters and brackets
     * @return a string
     */
    public String expressionExpand(String s) {
        
        Stack<String> stack = new Stack<String>();
        int number = 0;
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                number = number * 10 + (c - '0');
            } else if (c == '[') {
                stack.push(number + "");
                number = 0;
            } else if (c == ']') {
                String toAdd = popStack(stack);
                int count = Integer.parseInt(stack.pop());
                for (int j = 0; j < count; j++) {
                    stack.push(toAdd);
                }
            } else {
                stack.push(c + "");
            }
        }
        return popStack(stack);
    }
    
    public String popStack(Stack<String> stack) {
        Stack<String> buffer = new Stack<String>();
        while (!stack.isEmpty() && !Character.isDigit(stack.peek().charAt(0))) {
            buffer.push(stack.pop());
        }
        
        StringBuilder sb = new StringBuilder();
        while (!buffer.isEmpty()) {
            sb.append(buffer.pop());
        }
        
        return sb.toString();
    }
}

367. Expression Tree Build

我們需要用2個棧來解決,一個棧data用於存數字,一個棧op用於存操作符。從左往右掃描中綴表示式字串:

1)若遇到數字,則new一個節點,存到data棧裡面

2)若遇到左括號(,則new一個節點,存到op棧裡面

3)若遇到+-,若op棧有運算子的話(不是左括號)話,那就迴圈的把op棧頂運算子拿出來,把data棧的2個數字拿出來,湊成一個樹,然後壓回data棧。迴圈完後,再把遇到的+-壓入op棧。

4)若遇到*/,若op棧有運算子的話(不是*/)話,那就迴圈的把op棧頂運算子拿出來,把data棧的2個數字拿出來,湊成一個樹,然後壓回data棧。迴圈完後,再把遇到的*/壓入op棧。

5)若遇到右括號,若op棧頂的運算子不是左括號的話,那就迴圈的把op棧頂運算子拿出來,把data棧的2個數字拿出來,湊成一個樹,然後壓回data棧。直到遇到左括號,然後把左括號pop出來。

有個小技巧就是可以在紙上畫2個棧來模擬一下整個流程,這樣就會清晰很多。不必死記硬背,隨便拿出一個例子,然後onsite的時候拿出白板畫一下模擬一下流程。思路整理順暢後,程式碼自然就水到渠成了。

/**
 * Definition of ExpressionTreeNode:
 * public class ExpressionTreeNode {
 *     public String symbol;
 *     public ExpressionTreeNode left, right;
 *     public ExpressionTreeNode(String symbol) {
 *         this.symbol = symbol;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param expression: A string array
     * @return: The root of expression tree
     */
    public ExpressionTreeNode build(String[] expression) {
        Stack<ExpressionTreeNode> data = new Stack<ExpressionTreeNode>();
        Stack<ExpressionTreeNode> op = new Stack<ExpressionTreeNode>();
        
        for (String s : expression) {
            if (Character.isDigit(s.charAt(0))) {
                data.push(new ExpressionTreeNode(s));
            } else if (s.equals("(")) {
                op.push(new ExpressionTreeNode(s));
                // +-優先順序很低,需要給其他操作符讓路
            } else if (s.equals("+") || s.equals("-")) {
                while (!op.isEmpty() && !op.peek().symbol.equals("(")) {
                    ExpressionTreeNode node = op.pop();
                    ExpressionTreeNode a = data.pop();
                    ExpressionTreeNode b = data.pop();
                    node.right = a;
                    node.left = b;
                    data.push(node);
                }
                op.push(new ExpressionTreeNode(s));
                // */只需要給同級別的讓路
            } else if (s.equals("*") || s.equals("/")) {
                while (!op.isEmpty() && (op.peek().symbol.equals("*") || op.peek().symbol.equals("/"))) {
                    ExpressionTreeNode node = op.pop();
                    ExpressionTreeNode a = data.pop();
                    ExpressionTreeNode b = data.pop();
                    node.right = a;
                    node.left = b;
                    data.push(node);
                }
                op.push(new ExpressionTreeNode(s));
            } else if (s.equals(")")) {
                while (!op.peek().symbol.equals("(")) {
                    ExpressionTreeNode node = op.pop();
                    ExpressionTreeNode a = data.pop();
                    ExpressionTreeNode b = data.pop();
                    node.right = a;
                    node.left = b;
                    data.push(node);
                }
                op.pop();
            }
        }
        
        // 操作符棧還有內容
        while (!op.isEmpty()) {
            ExpressionTreeNode node = op.pop();
            ExpressionTreeNode a = data.pop();
            ExpressionTreeNode b = data.pop();
            node.right = a;
            node.left = b;
            data.push(node);
        }
        
        if (data.isEmpty()) {
            return null;
        }
        return data.pop();
    }
}

對錶達式進行求值,幾乎跟上題的程式碼一模一樣,思路也是類似的。不再贅述了。反正也是用2個棧來解決,畫畫圖就能理解了:

public class Solution {
    /**
     * @param expression: an array of strings;
     * @return: an integer
     */
    public int calc(String op, String a, String b) {
        int x = Integer.parseInt(a);
        int y = Integer.parseInt(b);
        if (op.equals("*")) {
            return x * y;
        } else if (op.equals("/")) {
            return x / y;
        } else if (op.equals("+")) {
            return x + y;
        } else if (op.equals("-")) {
            return x - y;
        }
        return 0;
    }
    public int evaluateExpression(String[] expression) {
        Stack<String> data = new Stack<String>();
        Stack<String> op = new Stack<String>();
        
        for (String s: expression) {
            if (Character.isDigit(s.charAt(0))) {
                data.push(s);
            } else if (s.equals("(")) {
                op.push(s);
            } else if (s.equals("+") || s.equals("-")) {
                while (!op.isEmpty() && !op.peek().equals("(")) {
                    String operator = op.pop();
                    String b = data.pop();
                    String a = data.pop();
                    String res = calc(operator, a, b) + "";
                    data.push(res);
                }
                op.push(s);
            } else if (s.equals("*") || s.equals("/")) {
                while (!op.isEmpty() && (op.peek().equals("*") || op.peek().equals("/"))) {
                    String operator = op.pop();
                    String b = data.pop();
                    String a = data.pop();
                    String res = calc(operator, a, b) + "";
                    data.push(res);
                }
                op.push(s);
            } else if (s.equals(")")) {
                while (!op.isEmpty() && !op.peek().equals("(")) {
                    String operator = op.pop();
                    String b = data.pop();
                    String a = data.pop();
                    String res = calc(operator, a, b) + "";
                    data.push(res);
                }
                op.pop();
            }
        }
        
        while (!op.isEmpty()) {
            String operator = op.pop();
            String b = data.pop();
            String a = data.pop();
            String res = calc(operator, a, b) + "";
            data.push(res);
        }
        if (data.isEmpty()) {
            return 0;
        }
        return Integer.parseInt(data.pop());
    }
};

把一個表示式轉換為波蘭表示式,其實思路很簡單,就是先把他建立成一棵表示式樹,建樹可以用上面拿到build expression tree的程式碼,然後再利用先序遍歷整棵樹就能得到答案了:

class ExpressionTreeNode { 
    public String symbol; 
    public ExpressionTreeNode left, right; 
    public ExpressionTreeNode(String symbol) { 
        this.symbol = symbol; 
        this.left = this.right = null; 
    } 
}
public class Solution {
    /**
     * @param expression: A string array
     * @return: The Polish notation of this expression
     */
    public ExpressionTreeNode build(String[] expression) {  
        Stack<ExpressionTreeNode> data = new Stack<ExpressionTreeNode>();  
        Stack<ExpressionTreeNode> op = new Stack<ExpressionTreeNode>();  
          
        for (String s : expression) {  
            if (Character.isDigit(s.charAt(0))) {  
                data.push(new ExpressionTreeNode(s));  
            } else if (s.equals("(")) {  
                op.push(new ExpressionTreeNode(s));  
                // +-優先順序很低,需要給其他操作符讓路  
            } else if (s.equals("+") || s.equals("-")) {  
                while (!op.isEmpty() && !op.peek().symbol.equals("(")) {  
                    ExpressionTreeNode node = op.pop();  
                    ExpressionTreeNode a = data.pop();  
                    ExpressionTreeNode b = data.pop();  
                    node.right = a;  
                    node.left = b;  
                    data.push(node);  
                }  
                op.push(new ExpressionTreeNode(s));  
                // */只需要給同級別的讓路  
            } else if (s.equals("*") || s.equals("/")) {  
                while (!op.isEmpty() && (op.peek().symbol.equals("*") || op.peek().symbol.equals("/"))) {  
                    ExpressionTreeNode node = op.pop();  
                    ExpressionTreeNode a = data.pop();  
                    ExpressionTreeNode b = data.pop();  
                    node.right = a;  
                    node.left = b;  
                    data.push(node);  
                }  
                op.push(new ExpressionTreeNode(s));  
            } else if (s.equals(")")) {  
                while (!op.peek().symbol.equals("(")) {  
                    ExpressionTreeNode node = op.pop();  
                    ExpressionTreeNode a = data.pop();  
                    ExpressionTreeNode b = data.pop();  
                    node.right = a;  
                    node.left = b;  
                    data.push(node);  
                }  
                op.pop();  
            }  
        }  
          
        // 操作符棧還有內容  
        while (!op.isEmpty()) {  
            ExpressionTreeNode node = op.pop();  
            ExpressionTreeNode a = data.pop();  
            ExpressionTreeNode b = data.pop();  
            node.right = a;  
            node.left = b;  
            data.push(node);  
        }  
          
        if (data.isEmpty()) {  
            return null;  
        }  
        return data.pop();  
    }
    public void preTraversal(ArrayList<String> res, ExpressionTreeNode root) {
        if (root != null) {
            res.add(root.symbol);
            preTraversal(res, root.left);
            preTraversal(res, root.right);
        }
    }
    public ArrayList<String> convertToPN(String[] expression) {
        ExpressionTreeNode root = build(expression);
        ArrayList<String> res = new ArrayList<String>();
        preTraversal(res, root);
        return res;
    }
}

把一個表示式轉換為逆波蘭表示式,其實思路很簡單,就是先把他建立成一棵表示式樹,建樹可以用上面拿到build expression tree的程式碼,然後再利用後序遍歷整棵樹就能得到答案了:

class ExpressionTreeNode { 
    public String symbol; 
    public ExpressionTreeNode left, right; 
    public ExpressionTreeNode(String symbol) { 
        this.symbol = symbol; 
        this.left = this.right = null; 
    } 
}
public class Solution {
    /**
     * @param expression: A string array
     * @return: The Reverse Polish notation of this expression
     */
    public ExpressionTreeNode build(String[] expression) {  
        Stack<ExpressionTreeNode> data = new Stack<ExpressionTreeNode>();  
        Stack<ExpressionTreeNode> op = new Stack<ExpressionTreeNode>();  
          
        for (String s : expression) {  
            if (Character.isDigit(s.charAt(0))) {  
                data.push(new ExpressionTreeNode(s));  
            } else if (s.equals("(")) {  
                op.push(new ExpressionTreeNode(s));  
                // +-優先順序很低,需要給其他操作符讓路  
            } else if (s.equals("+") || s.equals("-")) {  
                while (!op.isEmpty() && !op.peek().symbol.equals("(")) {  
                    ExpressionTreeNode node = op.pop();  
                    ExpressionTreeNode a = data.pop();  
                    ExpressionTreeNode b = data.pop();  
                    node.right = a;  
                    node.left = b;  
                    data.push(node);  
                }  
                op.push(new ExpressionTreeNode(s));  
                // */只需要給同級別的讓路  
            } else if (s.equals("*") || s.equals("/")) {  
                while (!op.isEmpty() && (op.peek().symbol.equals("*") || op.peek().symbol.equals("/"))) {  
                    ExpressionTreeNode node = op.pop();  
                    ExpressionTreeNode a = data.pop();  
                    ExpressionTreeNode b = data.pop();  
                    node.right = a;  
                    node.left = b;  
                    data.push(node);  
                }  
                op.push(new ExpressionTreeNode(s));  
            } else if (s.equals(")")) {  
                while (!op.peek().symbol.equals("(")) {  
                    ExpressionTreeNode node = op.pop();  
                    ExpressionTreeNode a = data.pop();  
                    ExpressionTreeNode b = data.pop();  
                    node.right = a;  
                    node.left = b;  
                    data.push(node);  
                }  
                op.pop();  
            }  
        }  
          
        // 操作符棧還有內容  
        while (!op.isEmpty()) {  
            ExpressionTreeNode node = op.pop();  
            ExpressionTreeNode a = data.pop();  
            ExpressionTreeNode b = data.pop();  
            node.right = a;  
            node.left = b;  
            data.push(node);  
        }  
          
        if (data.isEmpty()) {  
            return null;  
        }  
        return data.pop();  
    }
    public void postTraversal(ArrayList<String> res, ExpressionTreeNode root) {
        if (root != null) {
            postTraversal(res, root.left);
            postTraversal(res, root.right);
            res.add(root.symbol);
        }
    }
    public ArrayList<String> convertToRPN(String[] expression) {
        ExpressionTreeNode root = build(expression);
        ArrayList<String> res = new ArrayList<String>();
        postTraversal(res, root);
        return res;
    }
}