繁体   English   中英

打印给定字符串中所有可能的子字符串,而无需重复字符

[英]print all possible sub-strings in a given string without repetition of charactes

我在这里找到了仅打印最大子字符串的子字符串程序。 但是我正在尝试编写代码以打印给定字符串中的所有可能的子字符串,并且在所有这些子字符串中,最大的子字符串也打印在控制台上。因此,任何人都可以在不使用我尝试过该程序的String方法的情况下帮助我做到这一点但是我在不重复下面的字符的情况下得到字符串

public class SubSring {
     static Scanner sc = new Scanner(System.in);
        static String str = sc.nextLine();

        public static void main(String[] args) {
           String store="";
            for (int i = 0; i < str.length(); i++) {
                if (store.indexOf(str.charAt(i))<0) {
                    store = store+str.charAt(i);
                }
            }
            System.out.println("Result word " +store);

        }

    }

当前所拥有的内容将循环遍历str所有字符,如果字符串中当前不存在它们,则将它们添加到store中。 因此, store本质上将是删除了重复项的str的副本。

为了获取所有可能的str子字符串,您需要将store更改为字符串的集合。 LinkedList可能是一个适当的选择,因为您不知道会有多少个子字符串,这将使您轻松添加任意数量的结果。

因此,现在您可以放置​​结果了,您需要找到所有可能的子字符串。 为此,您将需要两个循环。 一个将确定子字符串的开始位置,另一个将确定结束位置。 这两个循环的索引之间的所有内容都是有效的子字符串,您可以将其添加到结果列表中。

因此,您的主要方法应包含以下内容:

        List<String> store = new LinkedList<String>();
        for (int i=0; i< str.length(); i++) {
            String substring = String.valueOf(str.charAt(i));
            // This is a valid substring so add to results
            store.add(substring);
            // Loop through the rest of the characters in str adding each
            // character to the substring variable.
            for (int j=i+1; j<str.length(); j++) {
               if (substring.indexOf(str.charAt(j)) < 0) {
                  substring += str.charAt(j);
                  // Add each substring to list of results
                  store.add(substring);
               }
            }
        }

然后,您可以遍历store每个字符串并打印出来。

在现实世界中,您可能需要将可能的子字符串存储在集合中以进行进一步处理,但是如果您的要求是简单地打印出每种可能性,则可以在没有如下列表的情况下执行此操作:

           for (int i=0; i< str.length(); i++) {
                String substring = String.valueOf(str.charAt(i));
                // This is a valid substring so print to console
                System.out.println(substring);
                // Loop through the rest of the characters in str adding each
                // character to the substring variable.
                for (int j=i+1; j<str.length(); j++) {
                  if (substring.indexOf(str.charAt(j)) < 0) {
                    substring += str.charAt(j);
                    // Each of these is a valid substring so print to console
                    System.out.println(substring);
                  }
                }
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM