簡體   English   中英

遞歸 - 將括號設置為字符串字符

[英]Recursion - Setting brackets to string characters

我的編程任務有問題。 我的工作是編寫一個獲取字符串並將其括起來的方法。 它應該以數組的形式返回。 例如:

String s = "ab";

那么數組必須是:

[ab, (a)b, ((a)(b)), a(b), (ab), (a)(b), ((a)b), (a(b))]

重要的是沒有結果出現兩次。 同樣重要的是,不應有括號直接包含另一對括號,例如((a))b(((a)(b))) 如果它為空或為零,則結果也必須是一個空數組。 ()是不允許的。 我只能使用 class String的方法。 Class 英國脫歐包括一個名為 append 的方法。 使用這種方法,我可以 append 一個字符串到我的數組末尾。 現在這是我到目前為止的代碼,但我不知道如何繼續。

public class Brackets {
    public static String[] bracket(BrExIt b, String s) {
        String[] array = new String[]{};
        if (s == null || s == "") {
            return array;
        }
        if (s.length() == 1) {
            array = b.append(array, s);
            array = b.append(array, "(" + s + ")");
            return array;
        } else {
            int a = 0;
            return bracket(b, s.substring(a + 1, s.length() - 1));
        }
    }
}

由於Java 9你可以使用String.codePoints方法得到一個stream超過字符,然后使用mapreduce的方法。

示例字符串:

String s = "ab";

首先將每個字母表示為這個字母的數組,這個字母用括號表示:

[a, (a)]
[b, (b)]

然后得到這些 arrays 的笛卡爾積

ab
a(b)
(a)b
(a)(b)

如果你想得到更多的括號,重復第一個操作:

[ab, (ab)]
[a(b), (a(b))]
[(a)b, ((a)b)]
[(a)(b), ((a)(b))]

Java代碼:

String s = "ab";

String[] array = s
        // stream over the characters of the string
        .codePoints()
        // Stream<String>
        .mapToObj(Character::toString)
        // represent each letter as an array of
        // this letter and this letter with brackets
        .map(str -> new String[]{str, "(" + str + ")"})
        // intermediate output
        .peek(arr -> System.out.println(Arrays.toString(arr)))
        // stream of arrays to a single array
        .reduce((arr1, arr2) -> Arrays.stream(arr1)
                .flatMap(str1 -> Arrays.stream(arr2)
                        .map(str2 -> str1 + str2))
                .toArray(String[]::new))
        // Stream<String[]>
        .stream()
        // Stream<String>
        .flatMap(Arrays::stream)
        // intermediate output
        .peek(System.out::println)
        // represent each string as an array of
        // this string and this string with brackets
        .map(str -> new String[]{str, "(" + str + ")"})
        // intermediate output
        .peek(arr -> System.out.println(Arrays.toString(arr)))
        // Stream<String>
        .flatMap(Arrays::stream)
        .toArray(String[]::new);

// final output
System.out.println(Arrays.toString(array));

最終 output:

[ab, (ab), a(b), (a(b)), (a)b, ((a)b), (a)(b), ((a)(b))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM