Question:
Given a parent string and a child string, return the position where the child string is arranged in any order for the first time in the parent string. If not, return-1. For example, if the parent string is qwertyuihgfd and the Child string is tyui, output 4
Analysis:
Because substrings are any combination, the combination of substrings is not fixed. You cannot start with substrings, but only from the parent string. Calculate the length of a substring, and cyclically extract the substring of the length of the substring from the first part. Then, loop through the substring to check whether the substring contains any character in the string of the fixed length, if the sub-string exists, it is removed until the loop ends. If the sub-string is removed empty, it indicates that the sub-string can be combined into the part of the parent string and the position of the master string is recorded.
Answer:
Static void Main ()
{
List <int> list = new List <int> ();
String M = "abcbdedbcbcbbcbbbc ";
String S = "bcb ";
For (int I = 0; I <= M. Length-S. Length; I ++) // cyclic mother string
{
String temp = M. Substring (I, S. Length); // capture the parent string
List <Char> chars = S. ToCharArray (). ToList (); // converts a substring.
For (int j = 0; j <temp. Length; j ++)
{
If (chars. Contains (temp [j])
{
Chars. Remove (temp [j]); // Remove the same character from the set
}
Else
{
Break; // jump out of the loop when there are non-contained characters and compare the Next string again
}
If (j = temp. Length-1) // use the number of j loops to determine the complete S character.
{
List. Add (I );
}
}
}
Foreach (int index in list)
{
Console. WriteLine ("string is {0} index: {1}", M. Substring (index, S. Length), index );
}
}
This article is from the "Gui suwei" blog