Expression Expand

来源:互联网 发布:数据库镜像与备份 编辑:程序博客网 时间:2024/06/03 16:50

Given an expression s includes numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string.

这个题目是一道典型的使用stack去做的题目,非常经典,一定要掌握

java

public class Solution {    /*     * @param s: an expression includes numbers, letters and brackets     * @return: a string     */    public String expressionExpand(String s) {        // write your code here        if (s == null || s.length() == 0) {            return s;        }        Stack<Object> stack = new Stack<>();        int num = 0;        for (int i = 0; i < s.length(); i++) {            if (Character.isLetter(s.charAt(i))) {                stack.push(s.charAt(i) + "");            } else if (Character.isDigit(s.charAt(i))) {                num = num * 10 + s.charAt(i) - '0';            } else if (s.charAt(i) == '[') {                stack.push(num);                num = 0;            } else if (s.charAt(i) == ']') {                transfer(stack);            }        }        StringBuffer sb = new StringBuffer();        while (!stack.isEmpty()) {            sb.append(stack.pop());        }        sb = sb.reverse();        return sb.toString();    }        private void transfer(Stack<Object> stack) {        StringBuffer sb = new StringBuffer();        int num = 0;        while (!stack.isEmpty()) {            Object obj = stack.peek();            if (obj instanceof String) {                sb.append((String)stack.pop());            } else {                num = (int)stack.pop();                break;            }        }        sb = sb.reverse();        for (int i = 0; i < num; i++) {            for (int j = 0; j < sb.length(); j++) {                stack.push(sb.charAt(j) + "");            }        }    }}



原创粉丝点击