Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,944 questions

51,885 answers

573 users

How to find all occurrences of all substring permutations (anagrams) in a string with Java

1 Answer

0 votes
import java.util.List;
import java.util.ArrayList;

public class MyClass {
    private static int SIZE = 256;
 
    private static boolean Compare(char[] arr_str, char[] arr_sub) {
        for (int i = 0; i < SIZE; ++i) {
            if (arr_str[i] != arr_sub[i])
                return false;
        }
     
        return true;
    }
 
    public static List<Integer> find_substring_permutations(String str, String sub) {
        List<Integer> result_list = new ArrayList<>();
         
        char[] countSub = new char[SIZE];
        char[] countStr = new char[SIZE];
     
        for (int i = 0; i < sub.length(); i++) {
            (countSub[sub.charAt(i)])++;
            (countStr[str.charAt(i)])++;
        }
 
        for (int i = sub.length(); i < str.length(); i++) {
            if (Compare(countSub, countStr))
                result_list.add(i - sub.length());
     
            countStr[str.charAt(i)]++;
            countStr[str.charAt(i - sub.length())]--;
        }
     
        if (Compare(countSub, countStr))
            result_list.add(str.length() - sub.length());
     
        return result_list;
    }
    public static void main(String args[]) {
        // 0 CBA : 5 BAC : 11 ABC : 12 BCA : 13 CAB : 21 ACB : 26 CAB
        String s = "CBAxyBACdarABCABbcapoACBqtCAB"; 
        String sub = "ABC";
         
        List<Integer> result = find_substring_permutations(s, sub);
 
         System.out.println(result.toString());
    }
}
 
 
 
 
/*
run:
 
[0, 5, 11, 12, 13, 21, 26]
 
*/

 



answered Jan 2, 2022 by avibootz
...