解析字符串的递归方法

时间:2020-01-14 19:16:10

标签: java string recursion

我有一个字符串“ {x {y} {a {b {c} {d}}}}” 并希望递归打印。

x
-y
-a
--b
---c
---d

这是我到目前为止所拥有的-

private static void printPathInChild2(String path) {

        if (path.length() == 0) {
            return;
        }
        if (path.charAt(0) == '{') {
            for (int i = 0; i < path.length(); i++) {
                if (path.charAt(i) == '{' && i != 0) {
                    String t1 = path.substring(0,i);
                    System.out.println(t1);
                    printPathInChild2(path.substring(i));
                } else if (path.charAt(i) == '}') {
                    String t2 = path.substring(0, i+1);
                    System.out.println(t2);
                    printPathInChild2(path.substring(i+1));
                }
            }
        }
    }

挣扎于终止逻辑

1 个答案:

答案 0 :(得分:2)

如果要添加取决于嵌套深度的'-'字符,则应将第二个参数传递给递归调用,以跟踪'-'字符的前缀。

遇到“ {”时,请在前缀前添加“-”。

遇到“}”时,将从前缀中删除“-”。

遇到其他任何字符时,将打印前缀,后跟该字符。

template <typename T>
struct vector {
    typename direction_trait<typename T::trait>::direction_t direction;
};

当您通过以下方式调用此方法时:

private static void printPathInChild2(String path,String prefix) {
    if (path.length() == 0) {
        return;
    }
    if (path.charAt(0) == '{') {
      printPathInChild2(path.substring(1),prefix + "-");
    } else if (path.charAt(0) == '}') {
      printPathInChild2(path.substring(1),prefix.substring(0,prefix.length()-1));
    } else {
      System.out.println (prefix.substring(1) + path.charAt(0));
      printPathInChild2(path.substring(1),prefix);
    }
}

您得到:

printPathInChild2("{x{y}{a{b{c}{d}}}}","");

(我看到您的预期输出'd'中有4个'-',但我认为这是一个错误,因为'd'具有与'c'相同的嵌套级别,因此它应该有3个'-' s。

该方法也可以编写如下:

x
-y
-a
--b
---c
---d