An example of string SEARCH

Source: Internet
Author: User

 

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.