CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program {
public static void Main() {
string val = "foobarfoobar";
Console.WriteLine(string.Join(" ", FindSubstring(val, new [] {
"foo",
"bar"
})));
//Console.WriteLine(FindSubstring(val, new [] { "foo", "bar" }));
}
static IList < int > FindSubstring(string s, string[] words) {
var list = new List < IList < string >> ();
DoPermutation(words, 0, words.Length - 1, list);
return TrackIndexes(s, list);
}
static IList < IList < string >> DoPermutation(string[] str, int start, int end, IList < IList < string >> list) {
if (start == end) {
list.Add(new List < string > (str));
} else {
for (var i = start; i <= end; i++) {
Swap(ref str[start], ref str[i]);
DoPermutation(str, start + 1, end, list);
Swap(ref str[start], ref str[i]);
}
}
return list;
}
static void Swap(ref string a, ref string b) {
var temp = a;
a = b;
b = temp;
}
static List < int > TrackIndexes(string pattern, IList < IList < string >> aLst) {
int count = 0;
List < string > strings;
List < int > indexes = new List < int > ();
foreach(var item in aLst) {
string str = "";
strings = new List < string > {
String.Concat(item)
};
foreach(var list in item) {
str += list;
if (str.Length == strings[0].Length && pattern.Contains(str)) {
indexes.AddRange(AllIndexesOf(pattern, str));
count += 1;
}
}
}
indexes.Sort();
return indexes.Distinct().ToList();
}
public static int[] AllIndexesOf(string str, string substr, bool ignoreCase = false)
{
if (string.IsNullOrWhiteSpace(str) || string.IsNullOrWhiteSpace(substr))
{
throw new ArgumentException("String or substring is not specified.");
}
var indexes = new List<int>();
int index = 0;
while ((index = str.IndexOf(substr, index, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) != -1)
{
indexes.Add(index++);
}
return indexes.ToArray();
}
}