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,940 questions

51,877 answers

573 users

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

1 Answer

0 votes
using System;
using System.Collections.Generic;
  
class Program
{
    private const int SIZE = 256;
  
    private static bool 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<int> find_substring_permutations(string str, string sub) {
        List<int> result_list = new List<int>();
          
        char[] countSub = new char[SIZE];
        char[] countStr = new char[SIZE];
      
        for (int i = 0; i < sub.Length; i++) {
            countSub[sub[i]]++;
            countStr[str[i]]++;
        }
  
        for (int i = sub.Length; i < str.Length; i++) {
            if (Compare(countSub, countStr))
                result_list.Add((i - sub.Length));
      
            countStr[str[i]]++;
            countStr[str[i - sub.Length]]--;
        }
      
        if (Compare(countSub, countStr))
            result_list.Add(str.Length - sub.Length);
      
        return result_list;
    }
    static void Main() {
        // 0 CBA : 5 BAC : 11 ABC : 12 BCA : 13 CAB : 21 ACB : 26 CAB
        string s = "CBAxyBACdarABCABbcapoACBqtCAB"; 
        string sub = "ABC";
          
        List<int> result = find_substring_permutations(s, sub);
  
        Console.WriteLine(string.Join(" ", result));
    }
}
  
  
  
  
/*
run:
  
0 5 11 12 13 21 26
  
*/

 



answered Jan 1, 2022 by avibootz
edited Jan 2, 2022 by avibootz
...