finding all distinct substring of a string

前端 未结 6 1792
借酒劲吻你
借酒劲吻你 2021-01-14 21:41

hello guys i was given homework problem where it asks me to find all distinct substring of a string. I have implemented a method which will tell you all the substrings of s

6条回答
  •  情书的邮戳
    2021-01-14 22:00

    There are two ways you could do this, not sure if your teacher permits but I am going to use a HashSet for uniqueness.

    Without using 'substring()':

    void uniqueSubStrings(String test) {
    HashSet < String > substrings = new LinkedHashSet();
    char[] a = test.toCharArray();
    for (int i = 0; i < test.length(); i++) {
        substrings.add(a[i] + "");
        for (int j = i + 1; j < test.length(); j++) {
            StringBuilder sb = new StringBuilder();
            for (int k = i; k <= j; k++) {
                sb.append(a[k]);
            }
            substrings.add(sb.toString());
        }
    }
    System.out.println(substrings);
    

    }

    Using 'substring':

        void uniqueSubStringsWithBuiltIn(String test) {
        HashSet substrings = new LinkedHashSet();
    
        for(int i=0; i

提交回复
热议问题