找到添加到给定字符串的所有子串组合

编程入门 行业动态 更新时间:2024-10-08 04:34:39
本文介绍了找到添加到给定字符串的所有子串组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个数据结构,其中包含所有可能的子字符串组合,这些组合可以添加到原始字符串中。例如,如果字符串是java,则有效结果将是j,ava,ja,v,a,无效结果将是ja,a或a,jav

I'm trying to create a data structure that holds all the possible substring combinations that add up to the original string. For example, if the string is "java" the valid results would be "j", "ava", "ja", "v", "a", an invalid result would be "ja", "a" or "a", "jav"

我很容易找到所有可能的子串

I had it very easy in finding all the possible substrings

String string = "java"; List<String> substrings = new ArrayList<>(); for( int c = 0 ; c < string.length() ; c++ ) { for( int i = 1 ; i <= string.length() - c ; i++ ) { String sub = string.substring(c, c+i); substrings.add(sub); } } System.out.println(substrings);

现在我正在尝试构建一个只包含有效子串的结构。但它并不那么容易。我正处于一个非常丑陋的代码的迷雾中,摆弄着索引,并没有接近完成,很可能完全是错误的路径。任何提示?

and now I'm trying to construct a structure that holds only the valid substrings. But its not nearly as easy. I'm in the mist of a very ugly code, fiddling around with the indexes, and no where near of finishing, most likely on a wrong path completely. Any hints?

推荐答案

以下是一种方法:

static List<List<String>> substrings(String input) { // Base case: There's only one way to split up a single character // string, and that is ["x"] where x is the character. if (input.length() == 1) return Collections.singletonList(Collections.singletonList(input)); // To hold the result List<List<String>> result = new ArrayList<>(); // Recurse (since you tagged the question with recursion ;) for (List<String> subresult : substrings(input.substring(1))) { // Case: Don't split List<String> l2 = new ArrayList<>(subresult); l2.set(0, input.charAt(0) + l2.get(0)); result.add(l2); // Case: Split List<String> l = new ArrayList<>(subresult); l.add(0, input.substring(0, 1)); result.add(l); } return result; }

输出:

[java] [j, ava] [ja, va] [j, a, va] [jav, a] [j, av, a] [ja, v, a] [j, a, v, a]

更多推荐

找到添加到给定字符串的所有子串组合

本文发布于:2023-11-30 07:32:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649182.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!