2019年秋招猿辅导笔试编程题解析字符串

猿辅导笔试

编程题的解析字符串

5
A11B
(AA)2A
((A2B)2)2G
(YUANFUDAO)2JIAYOU
A2BC4D2

输入如上,按照规则解析字符串
研究了下用栈写出来了,其实不难,加上笔试时间,和复杂的边界条件,程序就很难跑的完全通。
如果有好的递归写法,欢迎分享下

public class Main {
  public static void main(String[] args) {
    decodeString("A11B");
    decodeString("(AA)2A");
    decodeString("((A2B)2)2G");
    decodeString("(YUANFUDAO)2JIAYOU");
    decodeString("A2BC4D2");
  }

  public static String decodeString(String s) {
    Stack stack = new Stack();
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) == ')') {
        String str = "";
        while (!stack.peek().equals("(")) {
          str = stack.pop() + str;
        }
        stack.pop();
        String num = "";
        int w = 0;
        while (s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {
          w++;
          num = s.charAt(i + 1) + num;
          i++;
        }
        i = i - w + 1;
        int repeat = Integer.parseInt(num);
        String ret = "";
        for (int j = 0; j < repeat; j++) {
          ret = ret + str;
        }
        stack.push(ret);

      } else if (i + 1 > s.length() - 1 || s.charAt(i + 1) < '0' || s.charAt(i + 1) > '9') {

        String str = "";
        stack.push(s.charAt(i) + str);
      } else {
        int index = i;
        String num = "";

        while ((i + 1) <= s.length() - 1 && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {

          num = s.charAt(i + 1) + num;
          i++;
        }

        int nums = Integer.parseInt(num);
        String ret = "";
        for (int k = 0; k < nums; k++) {
          ret = s.charAt(index) + ret;
        }
        stack.push(ret);
        if (i + 1 >= s.length()) {
          break;
        }
      }
    }

    String result = "";
    while (!stack.isEmpty()) {
      result = stack.pop() + result;
    }
    System.out.println(result);
    return result;
  }
}

输出如下

AAAAAAAAAAAB
AAAAA
AABAABAABAABG
YUANFUDAOYUANFUDAOJIAYOU
AABCCCCDD

你可能感兴趣的:(2019年秋招猿辅导笔试编程题解析字符串)