Java Version: Expression Expand

2018-03-14  本文已影响0人  Star_C

Continued from previous post

This is a Java version of implementation.

class Result {
    public final String output;
    public final int stopAt;
    public Result(String o, int st) {
        this.output = o;
        this.stopAt = st;
    }
}

class NumScan {
    public final boolean success;
    public final int number;
    public final int digitStopAt;
    public NumScan(boolean suc, int num, int digSt) {
        this.success = suc;
        this.number = num;
        this.digitStopAt = digSt;
    }
}

public class Solution {
    /**
     * @param s: an expression includes numbers, letters and brackets
     * @return: a string
     */
    public String expressionExpand(String s) {
        return expand(s.toCharArray(), 0).output;
    }
    
    private String empty = "";
    
    private Result expand(char[] s, int from) {
        if (from >= s.length) return new Result(empty, from);
        NumScan numScan = scanNumber(s, from);
        if (numScan.success) {
            Result trunk = expand(s, numScan.digitStopAt + 1);
            String trunkStr = times(trunk.output, numScan.number);
            Result remain = expand(s, trunk.stopAt + 1);
            return new Result(
              trunkStr + remain.output,
              remain.stopAt
            );
        } else if (s[from] == '[') {
            return expand(s, from + 1);
        } else if (s[from] == ']') {
            return new Result(empty, from);
        } else {
            Result remain = expand(s, from + 1);
            return new Result(
                Character.toString(s[from]) + remain.output,
                remain.stopAt
            );
        }
    }
    
    private NumScan scanNumber(char[] s, int from) {
        if (!Character.isDigit(s[from]))
          return new NumScan(false, -1, from);
        int scanPos = from;
        String numStr = "";
        while (Character.isDigit(s[scanPos])) {
            numStr += s[scanPos];
            scanPos++;
        }
        return new NumScan(true, Integer.parseInt(numStr), scanPos - 1);
    }
    
    private String times(String text, int n) {
        StringBuilder b = new StringBuilder();
        for(int i = 0; i < n; i++)
          b.append(text);
        return b.toString();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读