Expression Expand

来源:互联网 发布:JS域名代码授权源码 编辑:程序博客网 时间:2024/06/07 06:03

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) + "");            }            if (Character.isDigit(s.charAt(i))) {                num = num * 10 + s.charAt(i) - '0' ;            }            if (s.charAt(i) == '[') {                stack.push(new Integer(num));                num = 0;            }            if (s.charAt(i) == ']') {                util(stack);            }        }        StringBuffer sb = new StringBuffer();        while (!stack.isEmpty()) {            sb.append((String)stack.pop());        }        sb.reverse();        return sb.toString();    }    private void util(Stack<Object> stack) {        Stack<String> temp = new Stack<>();        int num = 0;        String s = "";        while (true) {            Object s1 = stack.pop();            if (s1 instanceof String) {                temp.push((String)s1);            } else {                num = (Integer)s1;                break;            }        }        while (!temp.isEmpty()) {            s += (String)temp.pop();        }        for (int i = 0; i < num; i++) {            for (int j = 0; j < s.length(); j++) {                stack.push(s.charAt(j) + "");            }        }    }}


原创粉丝点击